使用猫鼬有条件地删除或添加文档数组中的元素

时间:2019-03-21 13:08:51

标签: javascript node.js mongodb mongoose

我从前端收到以下传入对象:

{
 name: "Test 1",
 sets: [1,2]
}

Mongo模式: Sets

name: {
        type: String
      },
tests   : [{
        type: Schema.Types.ObjectId,
        ref : 'Test'
    }]

我们假设该文档包含以下项目:

[
 {
  name: "Test Set 1",
  tests: [],
  id: 1
 },
 {
  name: "Test Set 2",
  tests: []
  id: 2
 }
]

然后使用此代码段尝试更新文档,但它总是从请求中删除最后一个项目。

const {sets} = req.body;
const {id} = req.params;

const tests = await Set.find({_id: {$in: sets}}).exec();

sets.forEach(async set => {
      tests.forEach(async test => {
        if (set !== test._id) {
         await Set.update({_id: test._id},
           {$addToSet: {tests: id}},
           {upsert: true})
       .exec((err, res) => console.log(err, res, 'ADDTOSET'));
     } 
else {
       await Set.updateMany({tests: {$elemMatch: {$eq: id}}},
          {$pull: {tests: id}}, {multi: true})
       .exec((err, res) => console.log(err, res, 'PULL'));
    }
 });
});

我如何更新有关setsreq.body数组的文档?

示例:

用户可以同时选择12这两个测试,然后tests模型中的所有Sets应该都拥有。

然后,用户决定仅选择1,然后应从数组中删除带有test id的{​​{1}},依此类推。

1 个答案:

答案 0 :(得分:0)

通过循环光标解决该问题:

id来自req.params,是test id

sets数组来自req.body

import mongoose from 'mongoose';

const cursor = Set.find({}).cursor();

for (let set = await cursor.next();
     set != null;
     set = await cursor.next()) 
      {
      if (!set.tests.includes(mongoose.Types.ObjectId(id)) && !sets.includes(set._id.toString())) {
         await Set.update({_id: set._id}, {$pull: {tests: id}}, {new: true, upsert: true}).exec();
      } else {
         await Set.updateMany({_id:  {$in: sets}}, {$addToSet: {tests: id}}, {new: true}).exec()
      }
}