Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

423
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!