Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Populate not working

Tags:

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.

like image 557
Teodor Avatar asked Oct 23 '14 11:10

Teodor


People also ask

How does populate work in Mongoose?

Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

How does Mongoose populate work under the hood?

Mongoose uses two queries to fulfill the request. The a collection is queried to get the docs that match the main query, and then the j collection is queried to populate the d field in the docs.

Can we use populate in aggregate MongoDB?

To use populate and aggregate in same statement with MongoDB and Node. js, we can call populate with the aggregation result returned from aggergate . to call aggregate to return a promise with the aggregation result.


1 Answers

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'); 
like image 131
JohnnyHK Avatar answered Sep 28 '22 00:09

JohnnyHK