简体   繁体   中英

Mongoose conditional populate with findById()

I'm attempting to populate a field only if the target model includes a certain property. Below, I want to populate the Book's product only if the Book's gift property is set to false, but it doesn't seem to work:

//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 } )

[EDIT] :

As suggested by Vinícius Belló, populating an existing document works.

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

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

You can receive the result without populate product then populate the result variable if gift is false. I recommend you to read this part of mongoose docummentation https://mongoosejs.com/docs/populate.html#populate_an_existing_mongoose_document . Let me know if this helped you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM