node.js - 将数组项推送到 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
解决方案
你必须在一个对象中完成所有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
)
});
我猜这可以解决问题,希望对您有所帮助
推荐阅读
- active-directory - Linux 服务器中的 Active Directory 用户限制
- r - 如何从 psych 包中 describeBy 的输出中排除变量?
- java - 使用 HttpURLConnection 将 Json 数据发布到 REST API 服务器
- mongodb - 使用 Perl 的 Mongodb 的 SSL 连接问题
- python - 使用 pyenv/python 3.7 在 ubuntu 18.04 上 pip install pygame
- google-cloud-sql - Cloud SQL 的 AutoResizeLimit
- ms-access - 如何在 MS Access VBA 中重绘和调整子报表控件的大小
- sql - 向表中插入新数据行后如何获取id?
- javascript - 每次点击同一个按钮时都会有不同的动作
- flutter - 在 Tab 点击事件上禁用 TabView 动画?