0

我正在尝试向脚手架 MEAN.js 用户实体添加几个属性。

locationName: {
    type: String,
    trim: true 
}

我还创建了另一个与用户连接的实体书。不幸的是,我认为我不太了解填充方法背后的概念,因为我无法使用 locationName 属性“填充”用户实体。

我尝试了以下方法:

/**
 * List of Books
 */
exports.list = function(req, res) { 
Book.find().sort('-created').populate('user', 'displayName', 'locationName').exec(function(err, books) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.jsonp(books);
        }
    });
};

不幸的是,我收到以下错误:

/home/maurizio/Workspace/sbr-v1/node_modules/mongoose/lib/connection.js:625
    throw new MongooseError.MissingSchemaError(name);
          ^
MissingSchemaError: Schema hasn't been registered for model "locationName".

有什么建议吗?谢谢干杯

4

1 回答 1

1

错误很明显,您应该有 locationName 的架构。

如果您的位置只是用户模型中的字符串属性并且不引用单独的模型,则您不需要也不应该使用它来填充它,它将简单地作为从 mongoose find返回的用户对象的属性返回()方法。

如果你想让你的位置成为一个独立的实体(不同的 mongodb 文档),你应该有一个定义你的位置对象的 mongoose 模型,也就是在你的app\models名称中有一个文件,例如:location.server.model.js包含类似:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var LocationSchema = new Schema({   
    _id: String, 
    name: String
   //, add any additional properties
});

mongoose.model('Location', LocationSchema);

请注意,此处的 _id 替换了自动生成的 objectId,因此它必须是唯一的,并且这是您应该在 User 对象中引用的属性,这意味着如果您有这样的位置:

var mongoose = require('mongoose'),   
    Location = mongoose.model('Location');
var _location = new Location({_id:'de', name:'Deutschland'});

你应该像这样在你的用户对象中引用它:

var _user=new User({location:'de'});
//or:
 var _user=new User();
_user.location='de';

那么您应该能够使用您的用户填充您的位置对象,如下所示:

User.find().populate('location').exec(function(err, _user) {
        if (err) {
            //handle error
        } else {
          //found user
          console.log(_user);
          //user is populated with location object, makes you able to do:
          console.log(_user.location.name);
        }
    });

我建议您进一步阅读mongodb 数据建模mongoose Schemas, Models, Population。

于 2014-11-06T07:44:37.647 回答