如何使用Mongoose和Node填充User对象

时间:2014-11-05 14:03:08

标签: node.js mongodb mongoose meanjs

我正在尝试向scaffolded MEAN.js用户实体添加一些属性。

locationName: {
    type: String,
    trim: true 
}

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

我尝试了以下内容:

/**
 * 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".

有什么建议吗? 谢谢 干杯

1 个答案:

答案 0 :(得分:1)

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

如果您的位置只是用户模型中的字符串属性而没有引用单独的模型,则您不需要也不应该使用populate,它只会作为返回的用户对象的属性返回来自mongoose find()方法。

如果你想让你的位置成为一个独立的实体(不同的mongodb文档),你应该有一个定义你的位置对象的猫鼬模型,也就是你的 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'});

你应该在你的User对象中引用它,如下所示:

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 data modelingmongoose模式,模型,人口。