【问题标题】:Mongoose conditional populate with findById()使用 findById() 进行 Mongoose 条件填充
【发布时间】:2020-12-22 03:57:24
【问题描述】:

仅当目标模型包含某个属性时,我才尝试填充字段。下面,只有当 Book 的 gift 属性设置为 false 时,我才想填充 Book 的 product,但它似乎不起作用:

//Schema
const bookSchema = new mongoose.Schema({

    gift: { type: Boolean, default: false },
    date: { type: Date, default: Date.now },
    author: { type: [authorSchema] },
    product: { type: [productSchema] }
}

// Conditional Populate
result = await Book
    .findById(bookID)
    .populate("author", "name")
    .populate("product", "price", { gift: false } )

[编辑]

按照 Vinícius Belló 的建议,填充现有文档是可行的。

// Conditional Populate
const result = await Book
    .findById(bookID)
    .populate("author", "name");

if (!result.gift) {
    await result
        .populate("product", "price")
        .execPopulate();
}

【问题讨论】:

    标签: javascript node.js mongodb mongoose populate


    【解决方案1】:

    您可以在不填充产品的情况下接收结果,然后如果礼物为假,则填充结果变量。我建议你阅读这部分猫鼬文档https://mongoosejs.com/docs/populate.html#populate_an_existing_mongoose_document

    【讨论】:

      猜你喜欢
      • 2020-12-08
      • 2016-08-06
      • 2021-10-11
      • 2014-11-09
      • 1970-01-01
      • 2015-08-07
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多