node.js - 追加 ObjectId 数组

标签 node.js mongodb mongoose mongodb-query

我在一个集合中有一个 ObjectId 数组,我想简单地添加另一个集合的 ObjectId。

router.post('/add/child', (req, res) => {
    console.log(req.body);
    switch (req.body.type) {
        case "category":
            Category.findOne({_id: req.body.to})
            .then(category => {
                if (!category) {
                    res.json({error: req.body.type + " not found"});
                }
                category.update({$push: {words: req.body.child}});
                console.log('category', category);
                res.json({category});
            })
            .catch(err => {
                console.log(err);
                res.json(err.response)
            })
        default:
            break;
    }
}

req.body 是:

{ type: 'category',
to: '5c312fd6ec0fff1c280aca19',
child: '5c323bed9b0f713aa0d49399' }

类别是:

category { words: [],
    _id: 5c312fd6ec0fff1c280aca19,
    title: 'Weather',
    [__v: 0 }

类别模型:

category: {
    title: {
        type: String,
        required: true
    },
    variation: {
        type: String
    },
    words: [{
        type: Schema.Types.ObjectId,
        ref: "words"
    }]
},

最佳答案

要追加数组,您需要 $push更新方法中的 运算符,如 findOneAndUpdatefindByIdAndUpdate 。如果您使用现有方法,则需要调用 push数组本身的方法,然后 save即:

Category.findById(req.body.to).then(category => {
    if (!category) {
        res.json({error: req.body.type + " not found"});
    }
    category.words.push(req.body.child);
    return category.save();
}).then(updatedCategory => {
    console.log('updatedCategory', updatedCategory);
    res.json({ category: updatedCategory });
})

更好的原子方法是使用 findOneAndUpdate方法如下:

Category.findByIdAndUpdate(req.body.to, 
    {'$push': {'words': req.body.child}},
    {new: true},
)
.exec()
.then(category => {
    console.log('category', category);
    if (!category) {
        res.json({error: req.body.type + " not found"});
    }
    res.json({ category });
})
.catch(err => {
    console.log(err);
    res.json(err.response)
})

关于node.js - 追加 ObjectId 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54121699/

相关文章:

node.js - Mongoose .js : How can I update a deep embedded document by its id?

node.js - 在发布到我们的消息端点时如何抑制和/或增加 15 秒超时消息? -- Node Js

javascript - 运行 mocha 单元测试时,如何避免我的 Q Promise catch block 在 NodeJS 回调式 API 中被调用两次?

linux - 使用 Linux shell 脚本向 mongodb 添加值

mongodb - 启动时将数据插入dockerized mongodb中

regex - 如何在mongodb中搜索逗号分隔的数据

node.js - 在kue中添加新作业时,有没有办法避免重复?

javascript - Babel 6 regeneratorRuntime 未定义

node.js - Mongoose - CastError : 'Cast to undefined failed for value "[object Object ]"at path "trainers"

javascript - Mongoose 一对多,如何获取类别的字段值