Home > front end >  Why does mongoose.exec() not contain data from the query
Why does mongoose.exec() not contain data from the query

Time:02-10

I'm really confused what's going on here:

when I use the following code I get my expected product

  const newProd = await models.Product.findOne({_id: new Buffer(util.HexUUIDToBase64(newProductData._id), 'base64').toString('hex')})
    .populate({
      path: 'SellerID',
      populate: { path: 'UserID' }})
      console.log(newProd)

However when I use this code then I get nothing for my product:

 const newProd = await models.Product.findOne({_id: new Buffer(util.HexUUIDToBase64(newProductData._id), 'base64').toString('hex')})
    .populate({
      path: 'SellerID',
      populate: { path: 'UserID' }}).exec(function (err, product) {
        console.log(err)
        console.log(product)
      })
      console.log(newProd)

I would expect my product to be passed to the callback but it's not. What exactly is going on here and how can I fix it?

CodePudding user response:

find() and exec() serve two different purposes.

The find() method is a database READ operation enabling function. It is present in both the native mongodb driver for node, as well as the Mongoose library which internally uses the mongodb drivers and is especially useful for imposing a fixed schema.

Now, in mongodb driver, if you use find(query), the query is automatically executed where as in mongoose it wouldn't. We need helper functions/ callbacks to get the operation to execute. exec is one such helper function. It goes something like: myPlaylist.findOne({'singer':'Adam Levine'}).exec()

Mongoose queries are not promises. They have a .then() function for convenience.

If you need a fully-fledged promise, use the .exec() function.

So, you could do a myPlaylist.findOne({'singer':'Adam Levine'}).then() but that would return a Mongoose/BlueBird (yet another library) promise and a typical JavaScript one.

Note: exec() takes an optional callback function. It's only when you do not use a callback that you get back a Promise.

  •  Tags:  
  • Related