Tuesday, 4 April 2017

Mongoose Finding data in Sub document

I have this model

//user notif schema

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

var UserNotifSchema = new mongoose.Schema({
    NotifType       : {type : Number}, 
    NotifData       : {
        User_source_id  : {type : Schema.Types.ObjectId, ref : 'User'}, // for course, forking
        Course_id       : {type : Schema.Types.ObjectId, ref : 'Course'}, // for course
        UserFile_id     : {type : Schema.Types.ObjectId, ref : 'UserFile'} // for forking
    },
    NotifTarget : [
        {type : Schema.Types.ObjectId, ref : 'User'}
    ],
    Created_at      : {type : Date, required : true, default : Date.now},
});


var UserNotif = mongoose.model('UserNotif', UserNotifSchema);
module.exports = UserNotif;

I create a model that contains user notification by NotifTarget. I want to get some notif to specific user and doing like this

var user_id = req.session.userLogin.UserId;

    NotifModel.find({'NotifTarget' : user_id})
                .populate('NotifTarget')
                .exec(function(err, doc){
                    if (err){
                        res.send(err);
                    }
                    else{
                        res.send(doc);
                    }
                })

This is ok when there only one array user_id in NotifTarget but return empty array when I give multiple data in NotifTarget. Are there any solution for this?



via Adi Sparta

No comments:

Post a Comment