복붙노트

[MONGODB] 만들기 mongoose.js 쿼리는 동 기적으로 실행

MONGODB

만들기 mongoose.js 쿼리는 동 기적으로 실행

나는 두 몽구스 컬렉션을 가지고있다. 첫 번째 저장 장소의 목록은, 두 번째는 장소 방문이다. 내 노드 코드를 통해 이동하고 각 장소에 방문의 목록을 얻을 문자열을 구축하려는 시도 JSON과 같은 I 출력이. 첫 번째 쿼리가 완료 두 번째는 이제까지 시작하기 전에 - 그들이 동 기적으로 실행되도록하는 방법이 있나요?

해결법

  1. ==============================

    1.당신은 Node.js를를 사용하는 경우 다음 U는 https://github.com/caolan/async를 사용해야합니다

    당신은 Node.js를를 사용하는 경우 다음 U는 https://github.com/caolan/async를 사용해야합니다

    여러 컬렉션에서 데이터를 가져올 때 당신은 당신의 쿼리 체인에 여러 번 있습니다.

    그것은 읽을 더 모듈화하는 코드가 복잡하고 어렵게 만들 것입니다. 만들 비동기를 사용하여 MongoDB를하고 Node.js를를 사용하여 모듈화

    내 프로젝트에서 예제 코드 :

    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
    }
    
  2. ==============================

    2.이 MongoDB를 / 몽구스 쿼리에 대한 기본 동기 API는 없다 (그리고 실용성에 하나를 원하지 않을 것이다). WiredPrarie 언급, 당신은 두 번째는 첫 번째 완료 후 시작하고 콜백을 실행하는, 쿼리를 체인해야한다. 다음은 그 예이다 :

    이 MongoDB를 / 몽구스 쿼리에 대한 기본 동기 API는 없다 (그리고 실용성에 하나를 원하지 않을 것이다). WiredPrarie 언급, 당신은 두 번째는 첫 번째 완료 후 시작하고 콜백을 실행하는, 쿼리를 체인해야한다. 다음은 그 예이다 :

    function findVisits(placesQuery,callback){
        Places.find(placesQuery).exec(function(err,places){
            if (err || !places.length){
                console.log('there was a problem');
                callback(err, null);
            }else{
                var visitQuery = ... //however you want to filter places
                Visits.find(visitQuery).exec(function(err2,visits){
                    if (err2 || !visits.length){
                        console.log('there was a problem');
                        callback(err2,null);
                    }else{
                        callback(null, visits)
                    }
                });
            }
        });
    }
    
  3. ==============================

    3.당신이 사용하는 경우 노드 당신이 활용할 수 8.x의 비동기 / await를 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

    당신이 사용하는 경우 노드 당신이 활용할 수 8.x의 비동기 / await를 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

    AWAIT 오퍼레이터는 약속까지 비동기 함수의 실행이 해결 일시 중지하고 값을 리턴한다. 코드가 더 동기 모양이 방법 :

    const query1 = MyModel.find({ name: /john/i }, null, { skip: 10 });
    const result1 = await query1.exec();
    
    const query2 = MyModel.find({ name: /john/i }, null, { skip: 100 });
    const result2 = await query2.exec();
    

    쿼리는 연속적으로 실행됩니다.

  4. ==============================

    4.당신은 () 쿼리를 그 때는 할 수 있습니다 요즘은 지원 약속을 몽구스. 예를 들면 :

    당신은 () 쿼리를 그 때는 할 수 있습니다 요즘은 지원 약속을 몽구스. 예를 들면 :

    app.get('/notifications', function (req, res, next) {
      Users.findOne({
        username: req.body.username,
        password: req.body.password,
      }).then(user => {
        if (!user) {
          res.json({success: false, message: "Username or password incorrect."});
          return;
        }
    
        return Notifications.find({
          user: user._id
        }).then(notifications => {
          res.json({success: true, notifications});
        });
      ).catch(error => {
        //console.error(error);
        //res.json({success: false, error: error.message});
        next(error);
      });
    });
    

    또한, 지금은 자바 스크립트가 비동기 await를을 가지고, 당신은 몇 줄을 저장하고 코드를 조금 평평 것이다, 그것을 사용할 수 있습니다 :

    app.get('/notifications', async (req, res, next) => {
      try {
        const user = await Users.findOne({
          username: req.body.username,
          password: req.body.password,
        });
        if (!user) {
          res.json({success: false, message: "Username or password incorrect."});
          return;
        }
    
        const notifications = await Notifications.find({
          user: user._id
        });
        res.json({success: true, notifications});
      } catch (error) {
        //console.error(error);
        //res.json({success: false, error: error.message});
        next(error);
      }
    });
    
  5. ==============================

    5.동기화하려면 나는 ES6-약속을 사용했다.

    동기화하려면 나는 ES6-약속을 사용했다.

    var Promise = require('es6-promise').Promise
      , mongoose = require('mongoose')
      , Schema = mongoose.Schema;
    
    // define schemas and models.
    var placeSchema = new Schema({
            name: { type: String },
            memo: { type: String }
        })
      , Places = mongoose.model('place', placeSchema)
      , visitSchema = new Schema({
            placeName: { type: String }, // foreign key for place.
            visitor: { type: String },
            comment: { type: String }
        })
      , Visits = mongoose.model('visit', visitSchema);
    
    // query for visits by visitor and place.
    function findVisitsWithPlace(visitor, place) {
        return new Promise(function (resolve, reject) {
            Visits.find({
                visitor: visitor,
                placeName: place.name
            }, function (error, visits) {
                if (error) {
                    reject(error);
                    return;
                }
    
                // build a result object you want.
                // ()
                resolve({
                    place: place,
                    visits: visits
                });
            });
        });
    }
    
    // functions for node route.
    module.exports = {
        // - access to "GET /placevisits/?visitor=Visitor-1".
        get: function (request, response) {
            var visitor = request.query.visitor;
    
            // - to get the places...
            Places.find({}, function (error, places) {
                Promise.all(places.map(function (place) {
                    // - run the child queries with parent object...
                    return findVisitsWithPlace(visitor, place);
                })).then(function (placeAndVisits) {
                    // - and get result.
                    // placeAndVisits have still contain visits empty.
                    // exclude them.
                    var result = [];
                    placeAndVisits.forEach(function (placeandvisit) {
                        if (placeandvisit.visits.length != 0) {
                            result.push(placeandvisit);
                        }
                    });
                    response.json(result);
                });
            });
        }
    };
    

    나는 다음과 같이 JSON을 얻었다.

    [
        {
            "place": {
                "_id": "564e58a1dbed862155771d46",
                "name": "Place-A",
                "memo": "A memo for Place A."
            },
            "visits": [
                {
                    "_id": "564e58cedbed862155771d49",
                    "placeName": "Place-A",
                    "visitor": "Visitor-1",
                    "comment": "A comment for Place A by Visitor-1"
                },
                {
                    "_id": "564e58dcdbed862155771d4a",
                    "placeName": "Place-A",
                    "visitor": "Visitor-1",
                    "comment": "2nd visit. Again comment for Place A by Visitor-1"
                }
            ]
        },
        {
            "place": {
                "_id": "564e58afdbed862155771d47",
                "name": "Place-B",
                "memo": "A memo for Place B."
            },
            "visits": [
                {
                    "_id": "564e58ebdbed862155771d4c",
                    "placeName": "Place-B",
                    "visitor": "Visitor-1",
                    "comment": "A comment for Place B by Visitor-1"
                }
            ]
        }
    ]
    
  6. ==============================

    6.여기 MongooseJS를 사용하여 의사 동기 요청을위한 또 다른 방법이다. 여기에 아이디어는 실행해야 할 쿼리의 큐를 만드는 것입니다. 그런 다음 큐가 소진 될 때까지 반복적으로 호출되는 함수를 만듭니다. 큐가 소진되면, 재귀 중지하고 응답 원래 요청 돌아온다. 이 코드의 모든 내 경로 처리기에서 캡슐화 그래서, 고속의 경로를 사용하고 있습니다. 이 경우는 HTTP POST합니다.

    여기 MongooseJS를 사용하여 의사 동기 요청을위한 또 다른 방법이다. 여기에 아이디어는 실행해야 할 쿼리의 큐를 만드는 것입니다. 그런 다음 큐가 소진 될 때까지 반복적으로 호출되는 함수를 만듭니다. 큐가 소진되면, 재귀 중지하고 응답 원래 요청 돌아온다. 이 코드의 모든 내 경로 처리기에서 캡슐화 그래서, 고속의 경로를 사용하고 있습니다. 이 경우는 HTTP POST합니다.

    var express = require('express');
    var router = express.Router();
    
    //POST /auth/create
    router.post('/create', function(req, res) {
        var queue = [
            {"schema": require('..\\models\\people.js'), "query": {username: req.body.username}},
            {"schema": require('..\\models\\members.js'), "query": {username: req.body.username}}
        ],
        retData = []; 
    
        var curTask = 0.
    
    
        function recurse()
        {   
            if(curTask < queue.length){
                    var task = queue[curTask];
                    task.schema.findOne(task.query, function(err, data){
                    retData.push(err || data);
                    curTask++;
                    recurse();
                })
            }else{
                res.json(retData);
            }
    
        }
    
        recurse();
    
    });
    
    
    
    module.exports = router;
    
  7. ==============================

    7.여기에 내가 오늘 밤에 일을 결국거야.

    여기에 내가 오늘 밤에 일을 결국거야.

    mongoose.createConnection("mongodb://localhost:27017/chemresearch")
    .then(async db => {
        const collection = db.collection("chemical");
        const all = collection.find({});
    
        while(all.hasNext()) {
            let chemical = await all.next();
            await work(chemical);
        }
    });
    

    작업 방법은 약속을 반환합니다.

    const work = (chemical) => new Promise((resolve, reject) => {
        const casNumber = chemical.casRegistryNumber;
        analysis(casNumber, (error) => {
            error ? reject(error) : resolve(casNumber);
        })
    });
    
  8. from https://stackoverflow.com/questions/17181248/making-mongoose-js-queries-run-synchronously by cc-by-sa and MIT license