如何在 MongoDB (mongoose) 中填充没有 ref 的数组字段?

How can I populate an array field without ref in MongoDB (mongoose)?

我有一个包含数组字段的架构。在这个数组字段中,我将插入 objects,其中包含作者的 _id 和作者的评论。 我想填充此字段,但我的架构没有参考。

这是我的模式

const Book = new Schema({
    name: {
        type:String,
        required: true 
    }
    authors: [{
        type: Array
    }]
})

const Author = new Schema({
    name: {
        type:String,
        required: true 
    }
    (... author's data)
})

我将在图书 collection 的作者字段中插入 objects:

insertAuthor = {
        _id:id,
        comment: 'comment'
    } 

它工作正常,但我无法填充作者字段。

有人可以帮我解决这个问题吗?

谢谢!!

如果 Schema 中未定义 ref,则可以在 populate 中指定 model。因此,据我了解,您需要通过填充 Author 来查询 Book

const books = await Book.find().populate({path: 'authors._id', model: 'Author'}).exec();

同样在您的 Book 模式中,如果您要插入问题中提到的 JSON 对象,则不需要在 JSON 中定义 type: Array。您可以按以下方式更新它。

const Book = new Schema({
    name: {
        type:String,
        required: true 
    }
    authors: [{}] //or [{_id: {type: Schema.Types.ObjectId}, comment: {type: String}}]
})