Assign return of findOne to a global variable Node Node.js

Asked

Viewed 430 times

0

I couldn’t do that assignment, so is there anything missing?

 global.pedido = db.collection('configuracoes').findOne({ parametro: "pedido_num"})
  • In this Collection I have {parameter:"pedido_num",value:100}

  • on the console looks like this:Order number: [Object Promise] { number: Promise { <pending> }, package: 'Gold package', coupon: ', discount: 0,

  • I made an edition according to the mongodb manual, but it didn’t help. global.request = db.Collection('configurations'). findOne({ parameter: "pedido_num"},{value:1});

3 answers

1

findOne returns a Promise, so the result will only be ready when it is solved. The result can be used in this way:

db.collection('configuracoes').findOne({ parametro: "pedido_num"}, function(err, document) {
  if ( !err ) global.pedido = document;
});

0

Another way to get the result of Promise is using await, but this command needs to be within an asynchronous function (just mark it as async).

try {
    global.pedido = await db.collection('configuracoes').findOne({ parametro: "pedido_num"});
} catch (error) {
    console.error(error);
}

0

You can try to put in a callback function intended to find an error if it exists. For example:

try {
  global.pedido = db.collection('configuracoes').findOne({ parametro: "pedido_num"});
} catch (error) {
console.log('>>>>>> Error: ', error);
}
  • Matheus, testei gives no error, but it is the question of the Promise and does not return the value

Browser other questions tagged

You are not signed in. Login or sign up in order to post.