简体   繁体   中英

Querying from [array of objects] with mongoose find

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 ie 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.

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){...});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM