user16390425
user16390425

Reputation:

Mongodb Node.js getting query result out of a function

I just want the function to return the result of a mongodb query, and I can't get it to not return a promise.

function findResult(sequence){
    return dbo.collection("counter").findOne({ name: sequence })
}

I've tried so many things like await, callbacks using .then etc. Examples would be really appreciated, can't find any up-to-date examples on how to do this.

Edit:

I'm using the result to auto increment.

function findResult(sequence) {
       return dbo.collection("counter")
           .findOne({ name: sequence })
           .then(function (res) {
               return res;
           })
           .catch(function (err) {
           });
   }

   let result = findResult('test');
   console.log(result)

And this still returns Promise { <pending> }

Upvotes: 1

Views: 459

Answers (2)

MohammadTausif Shaikh
MohammadTausif Shaikh

Reputation: 543

As DB queries are asynchronous process you need handle it differently, following are the ways to handle asynchronous process.

1) async/await

async function findResult(sequence) {
  return await dbo.collection("counter").findOne({ name: sequence });
}

// Function call
try {
   let result = await findResult(sequence);
}
catch(err){
// handle error;
}

2) Callback

function findResult(sequence, cb) {
  dbo.collection("counter").findOne({ name: sequence }, (err, res) => {
    if (err) {
      cb(err)
    } else {
      cb(null, res);
    }
  });
}

// Function call
let result = findResult(sequence, (err, res) => {
  if (err) {
    // handle error;
  } else {
    // handle result;
  }
});

3) Promise

function findResult(sequence) {
  return dbo
    .collection("counter")
    .findOne({ name: sequence })
    .then(function (res) {
      return res;
    })
    .catch(function (err) {
      // handle error;
    });
}

// Function call
let result = await findResult(sequence);

Upvotes: 3

Anku Singh
Anku Singh

Reputation: 954

As query returns promise so you have to use then when calling your function, you can try like this to fetch the result

function findResult(sequence){
  return new Promise((resolve, reject) => {
    dbo.collection("counter").findOne({ name: sequence }).then(result => {
      resolve(result);
    })
   .catch(err => reject(err));
  })
} 

findResult("sdfsd").then(res => {
   console.log(res)
});

Upvotes: 0

Related Questions