Search code examples
node.jsmongodbexpressmongoose

MongooseJS using find to find by reference


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);
        });
      });

Solution

  • In your latest comment you say that the company field of the Surveys collection is actually a string and not and ObjectId and that's why this isn't working. Because your schema definition declares company as an ObjectId, Mongoose will cast your req.query.company value to an ObjectId and then query for documents in Surveys where their company property is an ObjectId with the same value. So if company is a string in the database it won't match.

    If you update the company values in Surveys to be ObjectIds instead of strings then this will work.