Al Fahad
Al Fahad

Reputation: 2568

unable to populate documents using mongoose populate()

I am making an application in express using mongoose. I have a collection called users in which there is a filed called _subscriptions, which is an array of objects and each object contains a field named field which is an ObjectId for the documents of fields (this is another collection in my db).

I want to make such an API which after getting id parameter returns me a user form users collection with field attribute populated instead of its id in value of the field field. For this I am using populate method but it is not working.

This is screenshot showing users collection:

This is screenshot showing <code>users</code> collection

This is screenshot showing fields collection:

enter image description here

This is schema for field (File name Field.js):

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

var FieldSchema = new Schema(
    {
        _id: Schema.Types.ObjectId,  
        name: String,
        price: Number,
        _categories: [{
            type: Schema.ObjectId,
        }],
    }
);

module.exports = mongoose.model('Field', FieldSchema);`

This is schema and model for users

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
    _id: Schema.Types.ObjectId,
    salt: String,
    provider: String,
    name: String,
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    _subscriptions: [{
        field: {
            type: mongoose.Schema.ObjectId,
            ref: 'Field',
        },
        status: String,
        dateSubscribed: Date,
        payments: [{}]
    }],
    role: String,
});

module.exports = mongoose.model('User', UserSchema);

This is code for user router

var Field = require('../model/Field');
var express = require('express');
var router = express.Router();
var User = require('../model/User');

router.get('/',function(req, res, next) {
    User.find({}, function(err, result) {
        if (err) {
            console.log(err);
            res.send('something wrong');
        }
        res.status(200).send(result);
    }).populate( '_subscriptions.field').exec(function (err, story) {
        if (err) return handleError(err);
        console.log('Here!!!!!');
      });
});

router.get('/findById/:id',function(req, res, next) {
    var id = req.params.id;
    User.findById(id, function(err, doc) {
      if (err) {
        console.error('error, no entry found');
      }
      res.status(200).send(doc);
    }).populate('field').exec(function (err, story) {
        if (err) return handleError(err);
        console.log('Here!!!!!');
    });
});

router.get('/getSubscriptions/:id',function(req, res, next) {
    var id = req.params.id;
    User.findById(id, function(err, doc) {
      if (err) {
        console.error('error, no entry found');
      }
      var type = typeof(doc);
      res.status(200).send(doc);
    })
});
 module.exports = router;

This is where I have called app.use method:

enter image description here

And this is response I am getting using postman

enter image description here

I am looking forward for someones' assistance in resolving this issue as i am unable to identify my mistake. Your help in this regard will be highly appreciated.

Thanking in advance

Upvotes: 0

Views: 324

Answers (1)

Muhammad Danish
Muhammad Danish

Reputation: 335

What I have understood is, In the user collection, there is _subscriptions and in _subscriptions, there is field. If this is your schema, then you should pass "_subscriptions.field" as a parameter to the populate function not "field" as you have passed currently.

So, your code for user's sub route, /findById/:id, must be like this:

router.get('/findById/:id',function(req, res, next) {
    var id = req.params.id;
    User.findById(id, function(err, doc) {
      if (err) {
        console.error('error, no entry found');
      }
      res.status(200).send(doc);
    }).populate('_subscriptions.field').exec(function (err, story) {
        if (err) return handleError(err);
        console.log('Here!!!!!');
    });
});

Upvotes: 1

Related Questions