我在自己的代码中遇到了这个问题。我复制了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
所以集合名称来自哪里?我糊涂了。
感谢您提供的任何帮助。
答案 0 :(得分: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"
});
});