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