我正在使用 node.js+mongoose+websocket(它只是后端-主要用于培训)制作爱好的“civlike”游戏,并且我坚持使用“技术”-不知道如何实现它们。
第一个想法是“重载”一个 exec() 方法,并添加如下内容:
Techs.apply(result);
,但不能那样做 - 它是异步的,并且 exec() 无法访问返回的文档。
没有它,我每次查询文档时都必须手动应用它们——但我认为这不是最好的方法,也许我错了,或者这是唯一的方法?
因为它是异步的,所以你必须在你的回调函数中处理文档。我认为你想要做的是这个。
// 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
});