【问题标题】:How to populate the User object with Mongoose and Node如何使用 Mongoose 和 Node 填充用户对象
【发布时间】:2014-11-06 15:44:37
【问题描述】:

我正在尝试向脚手架 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".

有什么建议吗? 谢谢 干杯

【问题讨论】:

    标签: node.js mongodb mongoose meanjs


    【解决方案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 data modelingmongoose Schemas, Models, Population。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-03
      • 2021-12-20
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 2018-11-23
      • 2015-08-07
      • 2017-01-01
      相关资源
      最近更新 更多