Tuesday, 25 April 2017

Populate Data In mongoose not working properly?

I have the two collections user and userMapping The user object is mapped into the usermapping collection with other info. I am using referencing in it.

Here is the schema which I have created:

var userSchema = new userSchema({
    firstName: { type: String, required: true},
    middleName : String,
    lastName: { type: String, required: true},
    jobTitle : String,
    signumId : { type: String, required: true},
    //userGroupId : { type: String, required: true},
    emailAddress : { type: String, required: true, unique: true},
    contactNumber : String,
    status : Boolean,
    image : String,
    createdDate : String,
    lastUpdatedData :  String,
    lastLogin: String
});

var userModel = mongoose.model('User', userSchema);

And UserMapping schema is:

var userMappingSchema = new userMappingSchema({
    userId: {type :String, ref : 'User'},
    userGroupId : { type: String, required: true},
    createdDate : String,
    lastUpdatedData :  String
});

var userMappingModel = mongoose.model('UserMapping', userMappingSchema);

and after that I am trying to populate the data and I am getting the data only from the user collection, but not from the usermapping collection.

Here I is the code for the populate:

var User = require('../models/user').userModel;

var fetchUserList = function(req, res) {    
    User.find({})
        .populate('userId')
        .exec(function (err, result) {
        if(err) {
            res.json({"message":"Error On Fetching Users from DB", "errorCode":500 });
        }
        else {
            console.log(result);
            res.json({"message":"success", "errorCode":200, "data": result });
        }
    });

};

Can anybody help me where I am doing wrong, I am new to mongoDB.



via Anita Mehta

No comments:

Post a Comment