我正在使用node.js + mongoose + websocket制作一个“civlike”游戏(它只是后端 - 主要用于训练),我坚持使用“技术” - 不知道如何实现它们。
第一个想法是“重载”一个exec()方法,并添加如下内容:
Techs.apply(result);
,但不能这样做 - 它是异步的,exec()无法访问返回的文档。
没有它我必须每次查询文档时手动应用它们 - 但我不认为这是最好的方法,也许我错了或者它是唯一的方法吗?
答案 0 :(得分:0)
因为它是异步的,所以你必须处理回调函数中的文档。我想你要做的就是这个。
// docId is the _id passed from the client
Techs.findById(docId, function(err, doc) {
// This code executes after we've returned from MongoDB with the answer
// Now you can either updated it some code like this
doc.title = 'new title';
// Then after you've updated you need to call the save() function
doc.save();
// Now send the response to the client
response.end(doc); // this will send the JSON of the doc to the client
});
// Find a document based on a query
Techs.findOne({type: 'iphone' }, function(err, doc) {
// This code executes after we've returned from MongoDB with the answer
// Now you can either updated it some code like this
doc.title = 'new title';
// Then after you've updated you need to call the save() function
doc.save();
// Now send the response to the client
response.end(doc); // this will send the JSON of the doc to the client
});