猫鼬向没有工作的孩子推送参考

时间:2018-09-12 19:09:34

标签: mongoose mongoose-populate

我试图将ref推给MongoDB中的孩子,但我无法使其正常工作。我似乎完全按照该示例。如果有人可以帮助,我们将不胜感激。

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

var storySchema = new Schema({
  title: String
});

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

var author = new Person({
  _id: new mongoose.Types.ObjectId(),
  name: 'Ian Fleming',
  age: 50
});

var story1 = new Story({
    title: 'Casino Royale'
});

story1.save(function(err, story) {
    author.stories.push(story);
    author.save(function(err) {
        Person.findOne({ name: 'Ian Fleming' })
        .populate('stories')
        .exec(function(err, author) {
            console.log(author.stories[0]); // returns undefined
        })
    });
});

谢谢。

0 个答案:

没有答案