猫鼬不会在更新模型时插入数组

时间:2020-08-29 02:09:30

标签: node.js mongodb mongoose

我有一个模型,该模型由董事会和Trello之类的列表组成,我的模型是

const listSchema = mongoose.Schema({
    header: String,
    listItems: [String]
})

const BoardSchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    lists: [listSchema]
})

用户创建木板并重定向到该木板后,他应该创建一个列表,然后在该列表中添加项目

module.exports.AddList = async(req, res) => {

    const { id } = req.body;
    Board.findById(id).then((board) => {
            const list = {
                header: "List1",
                listItem: ['task', 'task2']
            }
            board.lists.push(list);
            board.save();
        }).catch((e) => {
            console.log(e);
        })
}

当我这样做时,它确实将模型插入数据库中,但是list []仅具有_id和header属性,而没有listItems,这是什么原因造成的?当我无法使用它们时,为什么list []中的每个对象都有自己的_id

 List.findById('5f49b4db98bcad61a84410e6').then((list) => {
             console.log(list)
         })

只返回null;

1 个答案:

答案 0 :(得分:0)

您不能像这样更新文档。请参阅以下文档。 现在使用async-await

的新语法
module.exports.AddList = async (req, res) => {
  try {
    const { id } = req.body;
    const board = await Board.findByIdAndUpdate(id, { $set: { header: "List1", listItem: ['task', 'task2'] } }, { new: true });
    //Do what to you want do with data.
  } catch (error) {
    console.log(error);
  }
}

在保存()之前您错过了await关键字

module.exports.AddList = async(req, res) => {

    const { id } = req.body;
    Board.findById(id).then((board) => {
            const list = {
                header: "List1",
                listItem: ['task', 'task2']
            }
            board.lists.push(list);
            await board.save();
        }).catch((e) => {
            console.log(e);
        })
}

https://mongoosejs.com/docs/tutorials/findoneandupdate.html