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.mongoose
Note: ObjectId, Number, String, and Buffer are valid for use as refsspa
今天在使用mongoose的populate来查询ref的文档,一直查不到,花了整整一天时间了,只怪没有看完上面的描述。code
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在源文档的顺序必须一致。
it
意思是说在find后找到的文档若是使用ref,必须按照顺序查找引用。
io
看来文档仔细看是很是重要的。省得浪费精力时间。console