2

I'm working on an app using MongoDB and Express.js.

I am creating a post handler that updates a toy (found by its id) with a new proposed name for the toy (which is pushed onto a nameIds array that contains the ids of the other proposed names):

router.post('/names', (req, res) => {
  const toyId = req.body.toyId;
  const name = req.body.newName;

  mdb.collection('names').insertOne({ name }).then(result =>
   mdb.collection('toys').findAndModify({
     query: { id: toyId },
     update: { $push: { nameIds: result.insertedId } },
     new: true
   }).then(doc =>
     res.send({
       updatedToy: doc.value,
       newName: { id: result.insertedId, name }
     })
   )
  )
});

However, when I test this, I receive this error:

name: 'MongoError',
message: 'Either an update or remove=true must be specified',
ok: 0,
errmsg: 'Either an update or remove=true must be specified',
code: 9,
codeName: 'FailedToParse'

I'm not new to MongoDB, but this simple call is baffling me.

Thanks for any help you can provide!

Adam White
  • 1,096
  • 3
  • 14
  • 28
  • 1
    Related https://stackoverflow.com/questions/24325687/nodejs-and-mongodb-findandmodify-need-remove-or-update & https://stackoverflow.com/questions/40029068/how-to-use-findandmodify-with-a-node-js-mongodb-driver & https://stackoverflow.com/questions/24648610/mongodb-findandmodify-node-js. Looks like you are missing required arguments. – s7vr Dec 13 '17 at 17:53
  • 2
    This is nodejs mongodb not mongo shell. So use node mongo commands and also add nodejs tag in your post – wrangler Dec 13 '17 at 17:57
  • Ah, got it. Thanks so much for your help! – Adam White Dec 13 '17 at 18:00

1 Answers1

0

That is the format for mongo shell. Using mongo driver you would call with these arguments:

.findAndModify( //query, sort, doc, options, callback
  { id: toyId }, //query
  [], //sort
  { $push: { nameIds: result.insertedId } }, // doc update
  { new: true }, // options
  function(err,result){ //callback
    if (err) {
      throw err
    } else {
      res.send({
        updatedToy: result.value,
        newName: { id: result.insertedId, name }
      })    
    }
  }
)
Bernardo Dal Corno
  • 1,858
  • 1
  • 22
  • 27