[英]Search in MongoDB
I have create a schema named "Process", which include some objects; 我创建了一个名为“ Process”的模式,其中包含一些对象; some of them are not required in POST. POST中不需要其中的一些。
So I made some documents that have 'ParentrProcess' object and some without it. 因此,我制作了一些带有“ ParentrProcess”对象的文档,而有些文档则没有。
I want to delete the document that with the following: 我要删除具有以下内容的文档:
I'll check the id that in the url: 我将检查网址中的ID:
Process.findOne({ _id: req.params.id }, function (err, obj)
If id is valid I want to search again in all documents to find if this Process._id is a ParentrProcess._id in any other documents 如果id有效,我想在所有文档中再次搜索以查找此Process._id是否为其他任何文档中的ParentrProcess._id
if false: delete the document 如果为假:删除文档
if true: I had 2 situations: 如果是,我有两种情况:
return error message 'You can not delete Process that contain Subprocess' 返回错误消息“您不能删除包含子流程的流程”
delete the documents and all related documents (Process & ParentrProcess) 删除文档和所有相关文档(流程和家长流程)
Process.findById(req.params.id )
.exec()
.then(doc => {
console.log("to database", doc);
if (doc) {
res.status(200).json({
process: doc,
});
} else {
res.status(404)
.json({ message: "No valid entry found for provided ID" });
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
});
Follow this code. 请遵循此代码。 You might reach where you want to. 您可能会到达想要的地方。
router.post("/:processId/", (req, res) => {
const process = new Process({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
...
parentId: req.params.parentId // you can add only the required fields
});
process.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "Posted successfully",
createdprocess: {
name: result.name,
...
parentId: result.parentId
}
});
Process.findOneAndUpdate({ _id: result.parenttId},
{ $push: { parentProcess: result._id} }, // use $push to update, $pull to remove.
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
Well i didnt understood your complete problem, but im guessing your need is close to this. 好吧,我不明白您的完整问题,但是我想您的需求接近于此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.