What is the right way to make a synchronous MongoDB query in Node.js?

后端 未结 3 1139
礼貌的吻别
礼貌的吻别 2020-11-29 01:50

I\'m using the Node.JS driver for MongoDB, and I\'d like to perform a synchronous query, like such:

function getAThing()
{
    var db = new mongo.Db(\"mydata         


        
3条回答
  •  旧巷少年郎
    2020-11-29 02:23

    ES 6 (Node 8+)

    You can utilize async/await

    await operator pauses the execution of asynchronous function until the Promise is resolved and returns the value.

    This way your code will work in synchronous way:

    const query = MySchema.findOne({ name: /tester/gi });
    const userData = await query.exec();
    console.log(userData)
    



    Older Solution - June 2013 ;)

    Now the Mongo Sync is available, this is the right way to make a synchronous MongoDB query in Node.js.

    I am using this for the same. You can just write sync method like below:

    var Server = require("mongo-sync").Server;
    var server = new Server('127.0.0.1');
    var result = server.db("testdb").getCollection("testCollection").find().toArray();
    console.log(result);
    

    Note: Its dependent on the node-fiber and some issues are there with it on windows 8.

    Happy coding :)

提交回复
热议问题