使用 Mongoose 一段时间后,我可能会做错。当你有太多回调时,我发现很难阅读,例如:
我想找到一个文档并更新它。我需要先找到它,然后update
将在回调内findOne
.
var sam = new Character({ name: 'Sam', inventory: {}});
Character.findOne({ name: 'Sam' }, function(err, character) {
console.log(character);
// now I want to update it.
character.update({... }, function(err, characterID) {
// now I want to know the size of the document after the update.
Character.findOne({ _id: characterID }, function(err, character) {
// Now update it again....
});
});
});
最终变成了意大利面条式的代码!
你明白我的意思吗?
有什么想法可以做得更好吗?
或者如果没有所有这些回调,mongodb 原生会更好?
EDIT:
Character.findOne({...}, function(err, character) {
return character.update(...);
}).select("-field1 -field2").then(function(data) {
//
}).catch(function(error) {
// Handle any error from all above steps
}).done();
Error:
TypeError: Character.findOne(...).select(...).then(...).catch(...).done is not a function