【问题标题】:Querying from [array of objects] with mongoose find使用 mongoose find 从 [array of objects] 查询
【发布时间】:2016-08-27 00:21:22
【问题描述】:

我有两个 Mongo 模式定义如下:

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

要求:我想获取与某个 _id 匹配的所有会议对象,即每个“用户”模式对象都是唯一的。 conferenceMembers 是一个“用户”对象数组

我做了什么:

这是一个帖子:

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);

但是,过滤器似乎在这里不起作用,我也尝试了 $elemMatch 但没有运气。

【问题讨论】:

  • 您的ConferenceSchema 中没有userId 字段。你确定你发布了正确的代码吗?
  • 您应该在find 标准中使用conferenceMembers 而不是userId。请参阅下面的答案。
  • 我的错,这里的用户 ID 应该是 ConferenceMemebers 的 '_id' 字段(它是一个对象数组),我把它放在 req 正文中,所以我只是在这里取它.

标签: javascript mongoose


【解决方案1】:

要获取conferenceMembers 中具有特定userId 的所有文档,您可以这样做:

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

如果您也想填充用户,可以使用 mongoose populate。

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

【讨论】:

    猜你喜欢
    • 2022-11-14
    • 1970-01-01
    • 2021-12-16
    • 2021-03-03
    • 2018-12-22
    • 2018-07-07
    • 1970-01-01
    • 2017-12-18
    • 2019-08-25
    相关资源
    最近更新 更多