MarcoS
MarcoS

Reputation: 17711

Mongoose: how do I update/save a document?

I need to save a document to a mongo collection.
I want to save the 'insertedAt' and 'updatedAt' Date fields, so I suppose I can't do it in one step...

This is my last try:

  my topic = new Topic(); // Topic is the model
  topic.id = '123'; // my univocal id, !== _id
  topic.author = 'Marco';
  ...

  Topic.findOne({ id: topic.id }, function(err, doc) {
    if (err) {
      console.error('topic', topic.id, 'could not be searched:', err);
      return false;
    }
    var now = new Date();
    if (doc) { // old document
      topic.updatedAt = now;
    } else { // new document
      topic.insertedAt = now;
    }
    topic.save(function(err) {
      if (err) {
        console.error('topic', topic.id, 'could not be saved:', err);
        return false;
      }
      console.log('topic', topic.id, 'saved successfully');
      return true;
    });
  });

But this way I end up duplicating records... :-(

Any suggestion?

Upvotes: 0

Views: 1206

Answers (2)

nurulnabi
nurulnabi

Reputation: 459

Rather than doing whatever you are doing I prefer a very easy way to updating document with upsert. For this you need to keep in mind don't use the model to create an instance to insert. You need to create an object manually.

//don't put `updatedAt` field in this document.
var dataToSave = {
    createdAt: new Date(),
    id: 1,
    author: "noor"
    .......
}

Topic.update({ id: 123 }, { $set:{ updatedAt: new Date() }, $setOnInsert: dataToSave}, { upsert: true }, function(err, res){
        //do your stuff here
})

This query will first check wether any document is there is the collection if yes then it will only update udpatedAt if not then it will insert the whole new document in the collection. Hope this answers your query.

Upvotes: 1

ifiok
ifiok

Reputation: 494

set timestamps to false in schema definition and then add the fields on creation as you would like.

See sample schema definition below:

var mongoose = require('mongoose')
    , Schema = mongoose.Schema;

var Topic = new Schema({
    id:{
        type:String,
        required: true
    },
    author:{
        type:String,
        required: true
    }
},{
    timestamps: false
});

Upvotes: 0

Related Questions