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

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 🙂

Leave a Comment