我正在尝试设置补丁API,以便可以创建动态查询以推送,拉取和设置猫鼬模式中的数据。我有很多可以使用set更改的值,但是我还有一个对象数组,当我需要插入时需要调用push,而当我需要删除项目时需要调用pull。我正在尝试找到将其组合成动态结构的最佳方法。
模式:
const StepSchema = new Schema({
position: {
type: Number,
required: true
},
name: {
type: String,
required: true
},
due_date: {
type: Date
},
status: [{
label: {
type: String,
enum: ['Inactive', 'In Progress', 'Flagged', 'Complete'],
default: 'Inactive'
},
user: {
type: Schema.Types.ObjectId,
ref: 'users',
},
date: {
type: Date
}
}],
comments: [{
user: {
type: Schema.Types.ObjectId,
ref: 'users',
required: true
},
body: {
type: String,
required: true
},
date: {
type: Date,
required: true
},
}],
});
Api:
router.patch('/',
async (req, res) => {
let setQuery = req.body;
let pushQuery = {};
let pullQuery = {};
//remove id from set query
delete setQuery.id;
//if there is a comment
if(req.body.comment){
pushQuery.comments = req.body.comment
}
//if I need to remove a comment
if(req.body.remove_comment){
pullQuery.comments = {_id: req.body.remove_comment.id}
}
//Push new status into array
if(req.body.status) {
pushQuery.status = {
label: req.body.status,
user: req.user._id,
date: new Date()
};
delete setQuery.status;
}
//update step
await Step.findByIdAndUpdate(req.body.id, {$set: setQuery, $push: pushQuery, $pull: pushQuery})
.then(step => {
if(!step){
errors.noflow = "There was a problem updating the step";
return res.status(400).json(errors);
}
res.json(step)
})
.catch(err => {
console.log(err);
res.status(404).json(err);
});
});
尝试将新状态推入文档时出现以下错误:
operationTime:时间戳{ bsontype:'Timestamp',低:1,高_: 1560978288},确定:0,错误码:'更新路径\'状态\'将 在\'status \'处创建冲突,代码:40,codeName: 'ConflictingUpdateOperators','$ clusterTime':{clusterTime: 时间戳{ bsontype:'Timestamp',low :1,high_:1560978288}, 签名:{哈希:[Object],keyId:[Object]}},
答案 0 :(得分:0)
哦,您正在对状态执行$ set和$ push。您的pushQuery试图使status
成为文档上的数组,而setQuery希望将其设置为实际主体上的任何值(我猜是同一对象。
一种快速修复方法是将其从设置的对象中删除:
delete setQuery.status
合理而稳定的方法是只从每个阶段真正需要的主体中取出东西。示例:
const { position, name, dueDate, status, comment, remove_comment } = req.body;
const setQuery = { position, name, dueDate };
const pushQuery = { status, comments: comment };
// ...
这样,您的查询就不会发生任何冲突。