问题描述
我有两个猫鼬收藏.第一个存储位置列表,第二个存储对位置的访问.我的节点代码经过检查,并尝试获取对每个地方的访问列表,并构建一个以JSON输出的字符串.第一个查询在第二个查询开始之前完成-有没有办法使它们同步运行?
I have two mongoose collections. The first stores a list of places, the second is visits to the places. My node code goes through and attempts to get the list of visits to each place and build a string that I output as JSON. The first query completes before the second ever starts - is there a way to make them run synchronously?
推荐答案
如果您使用的是node.js,则您应该使用 https://github.com/caolan/async
If you are using node.js then u should use https://github.com/caolan/async
当您必须从多个集合中获取数据时,必须多次链接查询.
when you have to fetch data from multiple collections you have to chain your queries multiple times.
这将使您的代码复杂且难以阅读,并且没有模块化.使用异步创建使用mongodb和node.js进行模块化
It will make your code complex and difficult to read and no modularity. Use async to createmodularity using mongodb and node.js
我的项目中的示例代码:
Example Code from my project :
var async = require('async');
var createGlobalGroup = function(socket, data) {
async.waterfall(
[
/**
* this function is required to pass data recieved from client
* @param {Function} callback To pass data recieved from client
*/
function(callback) {
callback(null, socket, data);
},
/**
* Step 1: Verify User
*/
verifyUser,
/**
* Step 2: Check User Access Rights And Roles
*/
checkUserAccessRightsAndRoles,
/**
* Step 3: Create Project
*/
createNewGlobalGroup], function(err, result) {
/**
* function to be called when all functions in async array has been called
*/
console.log('project created ....')
});
}
verifyUser = function(socket, data, callback) {
//do your query
/**
* call next function in series
* provide sufficient input to next function
*/
callback(null, socket, data, {
"isValidUser": true,
});
}
checkUserAccessRightsAndRoles = function(socket, data, asyncObj, callback) {
//do your query
if(condition) {
callback(null, socket, data, {
roles: result,
"isValidUser": asyncObj.isValidUser,
"userId": asyncObj.userId,
});
} else {
//no call back
}
}
var createNewGlobalGroup = function(socket, data, asyncObj, callback) {
//wanna stop then no callback
}
这篇关于使mongoose.js查询同步运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!