Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb findOne - return value [duplicate]

I need to fetch id of user from collection 'users' by calling a function and return it's value.

fetchId = (name) => {
        User.findOne({name: name}, (err, user) => {
            return user._id;
        });
    };

But this implementation returns null. What is the way to fix it?

like image 339
Adam Jakś Avatar asked Jul 18 '26 20:07

Adam Jakś


1 Answers

following your example, if you don't want to use promises, you can simply pass a callback from the caller and invoke the callback when you have the result since the call to mongo is asynchronous.

fetchId = (name, clb) => {
  User.findOne({name: name}, (err, user) => {
    clb(user._id);
  });
};

fetchId("John", id => console.log(id));

Otherwise you can use the promise based mechanism omitting the first callback and return the promise to the caller.

fetchId = name => {
  return User.findOne({name: name}).then(user => user.id);
}; 


fetchId("John")
 .then(id => console.log(id));
like image 128
Karim Avatar answered Jul 20 '26 10:07

Karim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!