【发布时间】:2016-06-13 05:24:51
【问题描述】:
尝试查询包含 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 时,我得到一个 null 或 undefined 报告。
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 调试。
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 的良好知识来使其正常工作。
任何帮助将不胜感激!
【问题讨论】: