这是我的模型代码
var postSchema = new mongoose.Schema({
created_by: {type: Schema.ObjectId, ref:'User', autopopulate: true }, //should be changed to ObjectId, ref "User"
created_at: {type: Date, default: Date.now},
text: String
});
var userSchema = new mongoose.Schema({
username: String,
password: String, //hash created from password
created_at: {type: Date, default: Date.now}
});
下面是我如何插入数据并尝试使用populate方法检索它的代码。
Post.create({text: 'farheen123',created_by: '5587bb520462367a17f242d2'}, function(err, post){
if(err) console.log("Farheen has got error"+err);
else console.log(post);
});
// 5587f5556e6f2b38244d02d1:已创建用户的_id
Post
.findOne({ _id: '5587f5556e6f2b38244d02d1' })
.populate('created_by')
.exec(function (err, story) {
if (err) return handleError(err);
console.log('The creator is %s', story);
// prints "The creator is Aaron"
});
我得到的结果如下。它为created_by提供numm引用,而不是提供该id的用户名和密码。
The creator is { _id: 5587f5556e6f2b38244d02d1,
text: 'farheen123',
created_by: null,
__v: 0,
created_at: Mon Jun 22 2015 17:15:25 GMT+0530 (IST) }
答案 0 :(得分:2)
创建Post模型的实例时,需要将_id
作为ObjectId
分配给用户,而不是字符串:
var ObjectId = require('mongoose').Types.ObjectId;
Post.create({
text: 'farheen123',
created_by: new ObjectId('5587bb520462367a17f242d2')
}, function(err, post) {
if(err) console.log("Farheen has got error"+err);
else console.log(post);
});