用findById填充猫鼬

问题描述

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

//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íciusBelló的建议,填充现有文档即可。

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

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

解决方法

您可以在不填充产品的情况下接收结果,然后在礼物为假的情况下填充结果变量。我建议您阅读猫鼬文件https://mongoosejs.com/docs/populate.html#populate_an_existing_mongoose_document的这一部分。让我知道这是否对您有帮助。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...