在数组 mongodb 中添加另一个项目

Add another item in array mongodb

我正在向数组中插入数据,但是当我插入数据时,它会覆盖整个数组,这是我用于更新数组的路由器

router.put('/editbloodbankarray', function(req, res) {
        var editUser = req.body._id; 
        var newName = req.body.bloodbank_array; 
        User.findOne({ _id: editUser }, function(err, user) {
            if (err) throw err; 

                user.bloodbank_array = newName; 

                // Save changes
                user.save(function(err) {
                    if (err) {
                        res.json({ success: false, message: 'error' }); 
                    } else {
                        res.json({ success: true, message: 'Name has been updated!' }); 
                    }
                });

        });             
    });

示例文档:

_id:5c8521c377df3158d0555db1,
bloodbank_array:
[
0:"1"
1:"2"
]

当我 update/insert 新项目例如:3..数组变为:

_id:5c8521c377df3158d0555db1,
bloodbank_array:
[
0:"3"
]

您正在覆盖现有数组。 下面是行

user.bloodbank_array = newName;

改为在 newName array 上执行 for 循环并推送 user.bloodbank_array 中的项目 喜欢

for(int i=0;i<newName.length;i++)
{
    user.bloodbank_array.push(newName[i]);
}

可以直接使用$push运算符来做(看here for more information) but since you already lookup the document first, you could just do user.bloodbank_array.concat(newName); instead of assigning a new value to the array like you do now with user.bloodbank_array = newName. The concat-function is a standard JS-function which inserts a new item at the end of an array. Fore more information you may read the mozilla article.