猫鼬有条件地用 findById() 填充

Mongoose conditional populate with findById()

我试图仅在目标模型包含某个 属性 时才填充字段。下面,我只想在 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();
}

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