Tony
Tony

Reputation: 167

using $set on db.collection.save

I'am trying to add to date fields and some user info fields to a document, when inserting it into mongo (using db.collection.save).

Here is my code:

    collection.save(
        {document},
        {
            $set: {
                "document.createdBy": "2",
                "document.updatedBy": "2",
                "document.created": new Date(),
                "document.updated": new Date()
            }
        },
        (err, result) => {
      if (err){
        res.status(500).json({ status: 'something is wrong' })
        //return next(err);
      }else{
        res.status(200).json({ status: 'ok' })
        //return next();
      }
    });

Mongo only inserts the document and none if the fields in the $set. Any ideas to what I'am doing wrong?

Upvotes: 1

Views: 333

Answers (1)

Ashh
Ashh

Reputation: 46481

There is no argument for the $set operator in .save() query in mongodb

So instead try to append the object before the query

document.createdBy = "2",
document.updatedBy = "2",
document.created = new Date(),
document.updated = new Date()

collection.save(document, (err, result) => {
  if (err){
    res.status(500).json({ status: 'something is wrong' })
    //return next(err);
  } else {
    res.status(200).json({ status: 'ok' })
    //return next();
  }
})

Upvotes: 1

Related Questions