本文介绍了使 mongoose.js 查询同步运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个猫鼬系列.第一个存储地点列表,第二个是对地点的访问.我的节点代码通过并尝试获取每个地方的访问列表并构建一个我输出为 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 查询同步运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 05:57