MongooseJS使用find来查找参考
我有这个mongoose纲要。
var mongoose = require ('mongoose') , dev = require ('../db').dev (); var schema = new mongoose.Schema ({ date: { type: Date, default: Date.now }, company: { type: mongoose.Schema.Types.ObjectId, ref: 'Company' }, questionnaire: { type: mongoose.Schema.Types.ObjectId, ref: 'Questionnaire' } }); module.exports = dev.model ('Survey', schema);
我只想find具有特定公司ID的调查。 我怎么做? 我试过(用我的Express处理程序):
app.get ('/survey', function (req, res) { Survey.find ({ company: req.query.company }).populate ('questionnaire').exec (function (err, surveys) { return res.json (surveys); }); });
在你最新的评论中,你说Surveys
集合的company
字段实际上是一个string,而不是ObjectId,这就是为什么这不起作用。 由于您的模式定义将company
声明为ObjectId,因此Mongoose会将您的req.query.company
值转换为ObjectId,然后在Surveys
中查询其company
属性为具有相同值的ObjectId的文档。 所以如果company
是数据库中的一个string,它将不匹配。
如果您将Surveys
的company
值更新为ObjectId而不是string,那么这将起作用。
你有没有尝试'company._id
app.get ('/survey', function (req, res) { Survey.find ({ 'company._id': req.query.company }).populate ('questionnaire').exec (function (err, surveys) { return res.json (surveys); }); });