【发布时间】: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