試圖查詢子文檔數組,它包含的ObjectId裁判,並找到一個項目。貓鼬查詢陣列的一個的ObjectId
該項目的ObjectId的,當我添加一個新的教訓,「分配」到一個特定的位置得到填充。
這貓鼬架構顯示我的意思。
var mongoose = require('mongoose');
var lessonNames = new mongoose.Schema({
day: {type: String },
name: {type: String},
startTime: {type: String},
endTime: {type: String}
});
var locationNames = new mongoose.Schema({
name: {type: String, required: true},
address: String,
lessons: [ { type: mongoose.Schema.Types.ObjectId, ref: 'lessonnames'}]
});
mongoose.model('lessonnames', lessonNames);
mongoose.model('locationnames', locationNames);
我已經添加了一個教程到一個位置,現在我試圖找到這個特定的課程。我嘗試了幾種方法,但都沒有爲我工作。每次我得到一個空或未定義當我輸出查詢到的console.log報道。
if (location.lessons && location.lessons.length > 0) {
loc
.findById(req.params.locationid)
.populate('lessons', '_id')
.exec(function (err, myLesson) {
console.log(myLesson.lessons)
});
當我執行上述語句時,我看到在nodejs控制檯中生成以下內容,並啓用了貓鼬調試。
Mongoose: locationnames.findOne({ _id: ObjectId("56d4b687c4bcb5681a870cb5") }) { fields: undefined }
GET /api/locations/56d4b687c4bcb5681a870cb5/lesson/56d4b687c4bcb5681a870cb4
Mongoose: lessonnames.find({ _id: { '$in': [ ObjectId("56d4b687c4bcb5681a870cb4") ] } }) { fields: { _id: 1 } }
下面的代碼行是console.log的輸出。如你所見,ObjectId被顯示爲課程數組的一部分。但我怎麼做這「選擇」這個的ObjectId,所以我可以用它引用一個教訓查詢。
[{"_id":"56d4b687c4bcb5681a870cb4"}]
搜索網頁,看到一些帖子對_id NOG是一個字符串類型,我應該投它是一個字符串。但我認爲應該可以用ObjectId來查詢它,但應該比較容易查詢它,但是我缺乏mongoose和mongodb的相關知識來使它工作。
任何幫助,將不勝感激!
非常感謝zangw!現在就像魅力一樣。猜猜我是在正確的道路上,而是用在了錯誤的方向.populate。 – Ralf