【问题标题】:How to query in mongoose for relational/nested schemas?如何在猫鼬中查询关系/嵌套模式?
【发布时间】:2020-08-12 22:33:06
【问题描述】:

我有 2 个 Mongoose (5.9.25) 模式模型。 一、GroupSchema模型:

const GroupSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    admins: {
        type: String,
        default: ""
    },
    blocked: {
        type: String,
        default: ""
    },
    createdBy: {
        type: mongoose.Types.ObjectId,
        required: true,
        ref: 'user',
    },
    members: {
        type: String,
        default: ""
    },
    privacy: {
        type: String,
        required: true,
        enum: ['public', 'private', 'deleted'],
    },

})

二、GroupPostSchema 模型:

const GroupPostSchema = new mongoose.Schema({
    user: {
        type: mongoose.Types.ObjectId,
        required: true,
        ref: 'user',
    },
    text: {
        type: String,
        required: true
    },
    group: {
        type: mongoose.Types.ObjectId,
        required: true,
        ref: 'group',
    },
    image: {
        type: String
    }
})

我正在尝试这样查询:

var search = {
    "group.privacy": "public"
}

GroupPostSchema.find(search).exec((err, data) => {
    // something
})

但是它返回的空数组[]

我已阅读此答案: Mongoose query for nested schema

但我想将GroupPostSchema.group 保留为对象而不是数组。

如何以最简单的方式做到这一点?

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:

    像这样检查没有exec

    const users = await User.find({'group.privacy': 'public'});

    【讨论】:

    • 显示错误:“await 仅在异步函数中有效”
    • 我实际上已经使用聚合器解决了这个问题。谢谢顺便说一句
    猜你喜欢
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 2021-03-23
    • 2020-05-23
    • 2019-03-22
    • 1970-01-01
    • 2019-04-05
    • 2020-07-02
    相关资源
    最近更新 更多