我是MongoDB和Node.JS的新手,我有一个问题是在同一路径中实现多个保存调用的正确方法是什么,并确保它们都能正常工作,或者没有。我想要的是,如果一次保存失败,他们都会这样做。这是一些代码。它按预期工作没有问题,但我觉得这是不好的做法。
我的Post
架构,正如您所看到的,它只是一些文本,然后是指向另一个对象的指针数组,名为Comment。
var postSchema = mongoose.Schema({
text: String,
comments : [{
type : mongoose.Schema.Types.ObjectId,
ref : "Comment"
}]
});
我的Comment
架构。它只是一些文字。
var commentSchema = mongoose.Schema({
commentText: String
});
现在,这是我的路线...
apiRoutes.post("/testCreateComment", function(request, response, next){
var commentText = request.body.commentText;
var testID = request.body.testID
if (!commentText || !testID) //ensures all data is there.
return next(new Error("Not all the information required was provided."));
var newComment = new Comment({
commentText : commentText
})
newComment.save(function(err) { //first save the new TestComment.
if (err) return next(err);
Post.findById(testID, function(err, found){ //second find the Post object.
if (err) return next(err);
found.comments.push(newComment)
found.save(function(err){ //third, save the Post object with the comment added to the array.
if (err) return next(err);
response.json(newComment.getReturn()); // returns some data to be sent
})
})
})
})
在此路线中,有三种方法必须成功才能使整个操作起作用。现在,例如,保存第一个save
,但无论出于何种原因,findById
都不成功。在这种情况下,我会在数据库中出现一个无用的评论。
我的问题是,确保所有三项运作都成功并确保上述问题不可能发生的正确方法是什么?