您的位置:首页 > 运维架构

mongoose 使用populate 需要注意的问题

2014-06-24 16:04 411 查看
So far we've created two Models. Our Person model has it's stories field set to an array of ObjectIds. The refoption is what tells Mongoose which model to use during population, in our case the Story model. All _ids we store here must be document _ids from the Story model. We also declared the Story _creator property as aNumber, the same type as the _id used in the personSchema. It is important to match the type of _id to the type of ref.

Note: ObjectId, Number, String, and Buffer are valid for use as refs

今天在使用mongoose的populate来查询ref的文档,一直查不到,花了整整一天时间了,只怪没有看完上面的描述。

1. 在文档关联使用ref一定要注意,关联的那个model只能匹配_id这个字段,你要是搞个自动生成的啥的一概无效。列举一下吧:

var _User = new Schema({
_id:Number,// 只支持ObjectId,Number,String,Buffer,就这几个引用类型,ref匹配的只有这个_id
name:String,
age:Number
});

var _Comment = new Schema({
comments:[{
text:String,
created_by:{type:Number,ref:'User'}//这个User是model名称,数据类型要于_id的数据类型一致。
}]
})

var userModel = mongoose.model('User',_User);
var commentsModel = mongoose.model('Comment',_Comment);

// 查询

commentModel.findOne({ })
.populate('comments.created_by')
.exec(function (err, commets) {
console.log(err,commets);
})

2. populate(ref1,ref2) ref1和ref2在源文档的顺序必须一致。

意思是说在find后找到的文档如果使用ref,必须按照顺序查找引用。

看来文档仔细看是非常重要的。免得浪费精力时间。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: