I have this Mongoose Schema.
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);
I want to find only the surveys which have a specific company id. How do I do that? I tried (with my Express handler):
app.get('/survey', function(req, res) {
Survey.find({ company: req.query.company })
.populate('questionnaire')
.exec(function(err, surveys) {
return res.json(surveys);
});
});
In your latest comment you say that the
companyfield of theSurveyscollection is actually a string and not and ObjectId and that’s why this isn’t working. Because your schema definition declarescompanyas an ObjectId, Mongoose will cast yourreq.query.companyvalue to an ObjectId and then query for documents inSurveyswhere theircompanyproperty is an ObjectId with the same value. So ifcompanyis a string in the database it won’t match.If you update the
companyvalues inSurveysto be ObjectIds instead of strings then this will work.