在猫鼬中更新数组内的文档

时间:2020-09-11 10:22:58

标签: node.js mongoose

我想更新我的答案对象在答案数组中。我正在使用以下模式

First()

我正在使用updateOne方法更新数据库中的答案。谁能解释这里缺少什么。我几个小时以来一直在努力解决这个问题

var jobs = await (from j in _ctx.Jobs
                  join v in _ctx.Visits on j.JobID equals v.JobID
                  join p in _ctx.Products on j.ProductID equals p.ProductID
                  where j.IsProcessed== true
                  group v by v.JobID
                  into g
                      select new
                      {
                          JobId = g.Key,
                          DueDate = g.Max(x => x.DueDate),
                          VisitID = g.OrderByDecending(x => x.DueDate).First().VisitID
                      }).ToListAsync();

我的结果成功了,但是答案没有在db中更新。 我对Question.updateOne方法感到困惑。 任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

如果您尝试基于id数组中的一个文档的answers进行查询,则需要提供{_id: answerId}来代替{'answers._id': answerId}。而且,如果您需要更新的文档作为结果,则应该使用findOneAndUpdate方法。

Question.findOneAndUpdate(
  { "answers._id": answerId },
  { $set: { "answers.$.answer": "some answer" } },
  { new: true },
  (err, data) => {
    // handle response
  }
);