簡體   English   中英

貓鼬:如何更新/保存文檔?

[英]Mongoose: how do I update/save a document?

我需要將文檔保存到mongo集合中。
我想保存'insertedAt'和'updatedAt'Date字段,所以我想我一步就做不到...

這是我的最后嘗試:

  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;
    });
  });

但是這樣我最終會復制記錄... :-(

有什么建議嗎?

與其做任何事情,我不喜歡使用upsert更新文檔的一種非常簡單的方法。 為此,請記住不要使用模型來創建要插入的實例。 您需要手動創建一個對象。

//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
})

此查詢將首先檢查是否有文檔存在集合,如果是,則僅更新udpatedAt ,否則將在整個集合中插入整個新文檔。 希望這能回答您的查詢。

將模式定義中的時間戳記設置為false,然后根據需要添加創建時的字段。

請參閱下面的示例架構定義:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM