Code within Mongoose promise never executes

78
March 31, 2018, at 7:32 PM

I am currently using Mongoose with my Express application within my controllers. So far, I've been importing the model, and then running queries against it with success. Now, I'm setting up a cron file (called cron.js) and have a file that imports it the same way, however when I run the file from a package.json script the code within the promise never executes; there is no return value. This is the code in the script which runs my file:

babel-node server/db/cron.js

I've tried a few things:

import User from '../models/user';
User.find({}, function(err, users)  {
      // these don't run:
      console.log(err);
      console.log(users);
    })
async function getUser() {
    // runs
    console.log('hi');
    let user = await User.findOne({ 'name' : 'ETH'})
    // doesn't run
    console.log(user);
}
getUser();
User.findOne({ name: 'bob' })
.exec((err, user) => {
  // doesn't run
  console.log('123')
}

When I console.log the model (User) and the function (User.find) they have been imported succesfully. I've also tried this with findOne.

Answer 1

You need to call .exec():

let user = await User.findOne({ 'name' : 'ETH'}).exec()

findOne() returns a Query which returns a Promise which you then call .exec()

http://mongoosejs.com/docs/api.html#findone_findOne http://mongoosejs.com/docs/api.html#query_Query-exec

READ ALSO
Allowing users to use either email or username for login using Passport, LocalStrategy

Allowing users to use either email or username for login using Passport, LocalStrategy

I am relatively new to web development, and I am creating a website with NodeJs and Express that would ask for a username and email when registeringCurrently, it only accepts username for login

94
Is it possible to re-render with express after using a request-promise

Is it possible to re-render with express after using a request-promise

I am using express and request-promiseI can't get it to re-render after my request-promise

71
Executing and then Breacking a command with no return after t minutes via Python3 SSH

Executing and then Breacking a command with no return after t minutes via Python3 SSH

I want to execute a remote SSH command in a Raspberry Pi using my Ubuntu PC for T amount of minutes and later break it

90
Send voice message using telepot in Python

Send voice message using telepot in Python

I'm trying to create a telegram bot that send message to a specific userEach time I try to send a voice message I get this error:

187