Monday, 15 May 2017

Mongoose findOneAndUpdate not returning raw Mongo response

I'm trying to determine whether the document was found in my findOneAndUpdate operation. If it wasn't, I return a 404 not found error. I figured I'd use the "passRawValue" option Mongoose provides, and check for a raw value- if raw is undefined, I know the doc was not found.

However regardless whether the doc is found or not, my raw value is undefined. I've verified that the doc I'm trying to update is in the DB at the time of the query by running a simple "findOne" query just before the update. Where am I going wrong?

let updateItemById = (userId, itemId, params, cb) => {

//this finds and prints the document I'm testing with -- I know its in the DB

  // Item.findOne({ "_id" : itemId, ownerId: userId }, (err, doc) => {
  //   if (doc) {
  //     console.log("This is the doc: ", doc);
  //   }
  // });

  Item.findOneAndUpdate({ "_id" : itemId, ownerId: userId },
    {
      $set: {
        params
      }
    }, { runValidators: 1, passRawResult: true}, (err, doc, raw) => {

    if (err) {
      //winston.log
      return cb(ErrorTypes.serverError(), false);
    }
    else if (raw) {
      return cb(null, true);
    }
    else {
      return cb(ErrorTypes.notFound(), false);
    }

  });
} 



via David Tamrazov

No comments:

Post a Comment