0

I have two Mongo schemas defined as follows:

var userSchema = new mongoose.Schema({
    email: String,
    password: String, //hash created from password
    firstName: String,
    lastName: String,
    comment:{userComment:String,adminComment:String},
    postalAddress: String,
    city: String,
    state: String,
    country: String,
    institution: String,
    privilege: {type: String, enum:['normal','chair','admin']},
    status: {type:String, enum: ['granted','removed','pending']},
    myConference:[{type:Schema.Types.ObjectId,ref:'Conference'}],
    mySubmission:[{type:Schema.Types.ObjectId,ref:'Submission'}]
});

var conferenceSchema = new mongoose.Schema({
    conferenceTitle: {type:String},
    conferenceDescription: String,
    conferenceStartDate:{type:Date, default: Date.now},
    submissionEndDate:{type:Date},
    reviewEndDate:{type:Date},
    **conferenceMembers:[{type:Schema.Types.ObjectId,ref:'User'}]**,
    conferenceSubmissions:[{type:Schema.Types.ObjectId,ref:'Submission'}],
    createdBy:{type:Schema.Types.ObjectId,ref:'User'},
    //chairMembers:[{type:Schema.Types.ObjectId,ref:'User'}],
    department:String
});

Requirement: I want to fetch all the Conference objects which match a certain _id i.e. unique for each 'User' schema object. conferenceMembers is an array of 'User' objects

What I did:

It's a POST:

var userId=req.body.userId

**Conference.find({userId: {$in: [Conference.conferenceMembers]}},function(err,conf){**
if(err){
                return res.send(500, err);
            }
return res.send(200,conf);

But, the filter doesn't seem to work here, I tried with $elemMatch as well but no luck.

3
  • There is no userId field in your ConferenceSchema. Are you sure you have posted correct code? Commented Aug 26, 2016 at 16:11
  • you should use conferenceMembers not userId in your find criteria. See the answer below. Commented Aug 26, 2016 at 16:22
  • My bad, the userID here is supposed to be the '_id' field for the conferenceMemebers (which is an array of objects) and which I put in req body earliers so I'm just fetching it here. Commented Aug 27, 2016 at 9:14

1 Answer 1

1

To fetch all the documents which has specific userId in conferenceMembers, you can do this:

Conference.find({conferenceMembers : userId}).exec(function(err,conf){...});

if you want to populate the users too you can use mongoose populate.

Conference.find({conferenceMembers : userId}).populate('conferenceMembers').exec(function(err,conf){...});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.