【问题标题】:Can not populate array of objects无法填充对象数组
【发布时间】:2021-12-29 18:32:48
【问题描述】:

编辑添加了 mongoose.model。

我对 mongodb 和 mongoose 还是很陌生。我无法将书籍填充给猫鼬中的作者。 任何人都可以帮助我吗?这是我的代码。我删除了不必要的字段

const authorSchema = mongoose.Schema({
    _id:{
        type: String,
        required: true,
        unique: true,
        trim: true
    },
    name: {
        type: String,
        required: true,
        trim: true
    },
    books: [{
        type: String,
        ref: "Book"
    }]
}, {_id:false})

const Author = mongoose.model('Author', authorSchema)

module.exports = {Author}

我的图书架构如下所示

const bookSchema = mongoose.Schema({
    _id:{
        type:String,
        required:true,
        unique:true,
        trim: true
    },
    name: {
        type: String,
        required: true,
        trim: true,
        unique: true
    },
    description:{
        type: String,
        trim: true,
        default: 'No description specified'
    },
    datePublished: {
        type: Date,
        trim: true,
        default: '01/01/2001'
    },
    author:{
        type: String,
        ref: 'Author',
        required: true
    }
}, {_id:false})
const Book = mongoose.model('Book', bookSchema)

module.exports = {Book}

这是将它们填充在一起的路线

AuthorRouter.get('/authors/:id', async(req, res)=>{
    const authorID = req.params.id
    try {
        const author = await Author.findById(authorID)
        try {
            const populated = await author.populate({path: 'books.book', select: 'name description -_id'})
            console.log(populated);
            res.status(201).send(populated)
        } catch (e) {
            res.status(401).send(`${e}\n Unable to populate categories`)
        }
        
    } catch (error) {
        res.status(401).send('Unable to find author')
    }
})

输出如下是空书籍数组:

{
    "_id": "123",
    "name": "testuser",
    "books": [],
    "__v": 0
}

【问题讨论】:

  • 你在代码的什么地方指定了Mongoose.model函数?
  • @Tyler2P 在模式的末尾。我刚刚将它们添加到代码中

标签: node.js mongodb express mongoose


【解决方案1】:

填充引用数组可以使用same way as a single ref。只需在查询中调用 populate 方法,就会返回一个文档数组来代替原来的 _id's。

你的情况是:

const populated = await author.populate({path: 'books', select: 'name description -_id'});

【讨论】:

    【解决方案2】:

    嘿,我修改了你的代码,尝试使用这个

    这是您的作者架构文件

    const Schema = mongoose.Schema;
    const authorSchema = mongoose.Schema({
        _id:{
            type: String,
            required: true,
            unique: true,
            trim: true
        },
        name: {
            type: String,
            required: true,
            trim: true
        },
        books: [{
            type: Schema.Types.ObjectId,
            ref: "bookSchema"
        }]
    }, {_id:false})
    
    const Author = mongoose.model('Author', authorSchema)
    
    module.exports = {Author}
    

    这是你的路线

    
    AuthorRouter.get('/authors/:id', async(req, res)=>{
        const authorID = req.params.id
        try {
            const author = await Author.findById(authorID)
            try {
                const populated = await author.find().populate('books');
                console.log(populated);
                res.status(201).send(populated)
            } catch (e) {
                res.status(401).send(`${e}\n Unable to populate categories`)
            }
            
        } catch (error) {
            res.status(401).send('Unable to find author')
        }
    })
    

    【讨论】:

      猜你喜欢
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-15
      • 2018-11-14
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多