我从前端收到以下传入对象:
{
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'));
}
});
});
我如何更新有关sets
中req.body
数组的文档?
示例:
用户可以同时选择1
和2
这两个测试,然后tests
模型中的所有Sets
应该都拥有。
然后,用户决定仅选择1
,然后应从数组中删除带有test
id
的{{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()
}
}