【问题标题】:mongoose's documentation example for population, gives an errormongoose 的人口文档示例,给出了一个错误
【发布时间】:2016-06-22 00:54:19
【问题描述】:

我在自己的代码中遇到了这个问题。我从Mongoose Query Population 的示例中复制了代码,看看我做错了什么。但我对他们的代码也有同样的问题。 问题在于exec回调中的日志:

console.log('The creator is %s', story._creator.name);
                                    ^

TypeError: Cannot read property '_creator' of null

这是代码。

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

var personSchema = Schema({
    _id     : Number,
    name    : String,
    age     : Number,
    stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
    _creator : { type: Number, ref: 'Person' },
    title    : String,
    fans     : [{ type: Number, ref: 'Person' }]
});

var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

现在使用模型,创建一个新的Person 并保存它。并保存一个故事并使其_creator等于Person模型的id,称为aaron

var aaron = new Person({ _id: 0, name: 'Aaron', age: 100 });

aaron.save(function (err) {
    if (err) return handleError(err);

    var story1 = new Story({
        title: "Once upon a timex.",
        _creator: aaron._id    // assign the _id from the person
    });

    story1.save(function (err) {
        if (err) return handleError(err);
        // thats it!
    });
});

Story
  .findOne({ title: 'Once upon a timex.' })
  .populate('_creator')
  .exec(function (err, story) {
       if (err) return handleError(err);
       console.log('The creator is %s', story._creator.name);
       // prints "The creator is Aaron"
});

更新: 在数据库中,我只有一个名为 poeple 的集合,只有一个文档:

{
    "_id": 0,
    "name": "Aaron",
    "age": 100,
    "stories": [],
    "__v": 0
}

代码中没有世界 people 那么集合名称来自哪里?我糊涂了。 感谢您提供的任何帮助。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate


    【解决方案1】:

    story1 被保存,直到它的回调函数被调用。请尝试将 Stroy.find 移动到story1.save 的回调函数中,如下所示。

    story1.save(function (err) {
        if (err) return handleError(err);
        Story
          .findOne({ title: 'Once upon a timex.' })
          .populate('_creator')
          .exec(function (err, story) {
               if (err) return handleError(err);
               console.log('The creator is %s', story._creator.name);
               // prints "The creator is Aaron"
        });
    });
    

    【讨论】:

    • 就是这样。谢谢。此外,代码中没有任何 people 字样。那么集合的名称来自哪里(人)?
    • @asedsami,这是您的问题的一个很好的答案stackoverflow.com/a/24669465/3011380
    猜你喜欢
    • 2014-08-26
    • 1970-01-01
    • 2014-01-07
    • 2012-12-24
    • 1970-01-01
    • 2020-06-13
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多