Search code examples
node.jsexpressmongoose

Mongoose Populate not working


Hello i have this Schema(called schema.js):

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var RoomSchema = new Schema({
  name: { type: String, required: true, index: { unique: true } },
  people: { type: Number, required: true },
  childrens: {type: Number, required: true},
  total: {type: Number, required: true}
});

var Room = mongoose.model('Room', RoomSchema);

var AvSchema = new Schema({
  roomId:  {type: Schema.Types.ObjectId, ref: 'Room'},
  people: { type: Number, required: true },
  childrens: {type: Number, required: true},
  total: {type: Number, required: true}
});

var Av = mongoose.model('Av', AvSchema);

module.exports = {
  Room: Room,
  Av: Av
};

in my Route file :

module.exports = function(app) {
  var model = require('../models/Schema');

  app.get('/api/rooms', function(req, res) {
    model.Room.find(function(err, rooms) {
      if (err)
        res.send(err);

      res.json(rooms);
    });
  });


  app.get('/api/av', function(req, res) {
    model.Av.find().populate('roomId').exec(function(err, av) {
      if (err)
        res.send(err);

      res.json(av);
    });
  });
};

A pic of the db : enter image description here

GET /api/rooms - response:

[{
  "_id": "5444d0dd9a31437167eea816",
  "name": "Single",
  "people": 1,
  "childrens": 1,
  "total": 4
}, {
  "_id": "5444d1009a31437167eea817",
  "name": "Double",
  "people": 2,
  "childrens": 2,
  "total": 10
}]

When i call api/rooms looks fine but when i call api/av i got an empty array [] .... Any idea what i do wrong? I should mention that i have inserted records in av collection for both roomsID

Thank you in advance.


Solution

  • By default, Mongoose pluralizes the model name to come up with the name of the collection, so Mongoose is looking in the avs collection instead of av.

    You can explicitly set the collection name by passing that as the third parameter to model:

    var Av = mongoose.model('Av', AvSchema, 'av');