Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Mongoose:如何更新/保存文档?_Javascript_Node.js_Mongodb_Mongoose - Fatal编程技术网

Javascript Mongoose:如何更新/保存文档?

Javascript Mongoose:如何更新/保存文档?,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我需要将文档保存到mongo集合。 我想保存'insertedAt'和'updatedAt'日期字段,所以我想我不能一步完成 这是我最后一次尝试: 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,

我需要将文档保存到mongo集合。 我想保存'insertedAt'和'updatedAt'日期字段,所以我想我不能一步完成

这是我最后一次尝试:

  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;
    });
  });
但这样我就可以复制记录了…:-


有什么建议吗?

在模式定义中将时间戳设置为false,然后根据需要在创建时添加字段

请参见下面的示例架构定义:

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

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

我更喜欢用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。如果没有,则将在集合中插入整个新文档。希望这能回答您的问题。

如果您不打算保存新的db记录,请不要创建新主题。找到{u id:…,然后doc.updatedAt=now和doc.save我只有在插入新文档时才能添加insertedAt…:-为什么不在创建过程中将其添加到文档中。因此:…topic.insertedAt=Date.now;这是我自己使用的最简单的解决方案…:-唯一的区别是,在升级之前,我使用新模型创建数据,我有:dataToSave.\u id=未定义;我正在启动并运行…:-谢谢!