Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

434
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda