首页 > 解决方案 > 将数组项推送到 mongoDb 中的数组类型列

问题描述

这是一个控制器,我试图在其中捕获多个候选 id(ObjectId) 并尝试将其存储在数组 Candidates 的数据库中。但是数据没有被推送到 Array 类型的 Candidates 列中。

routes.post('/Job/:id',checkAuthenticated,function(req,res){
var candidates=req.body.candidate; 
console.log(candidates);
Job.update({_id:req.params.id},{$push:{Appliedby : req.user.username}},{$push:{Candidates:{$each: 
candidates}}}
});

控制台屏幕输出

[ '5eb257119f2b2f0b4883558b', '5eb2ae1cff3ae7106019ad7e' ] //candidates

标签: node.jsmongodbexpressejsbackend

解决方案


你必须在一个对象中完成所有update操作($set, $push, $pull, ...),并且这个对象应该是update过滤器对象之后传递给方法的第二个参数

{$push:{Appliedby : req.user.username}},{$push:{Candidates:{$each: candidates}}

这将Appliedby仅更新数组,因为 update 中的第三个对象是为选项保留的(如 upsert、new、....)

你必须做这样的事情

{ $push: { Appliedby: req.user.username, Candidates: { $each: candidates } } }

那么整个查询应该是这样的

routes.post('/Job/:id', checkAuthenticated, function (req, res) {
    var candidates = req.body.candidate;
    console.log(candidates);

    Job.update(
        { _id: req.params.id }, // filter part
        { $push: { Appliedby: req.user.username, Candidates: { $each: candidates } } } // update part in one object
    )
});

我猜这可以解决问题,希望对您有所帮助


推荐阅读