【问题标题】:Multiple Document Upsert in MongooseMongoose 中的多个文档更新插入
【发布时间】:2018-01-13 10:02:36
【问题描述】:

你好,这是我的问题,

var poolSchema = mongoose.Schema({
        "topic_id": {
            type: Number,
            default: null,
            required: true
        },
        "document_id": {
            type: String,
            default: null,
            required: true
        },
        "project":{
            type:String,
            default: false,
            required: true
        },
        "createddate":{
            type:Date,
            default : Date.now
        }
    }, { collection: "sorguHavuzu" }); 

我有一个池文档数组,每个项目都有不同的字段值,如下所示:

var poolItems = [
                   {document_id :"FBIS3-50136" ,topic_id :"301" , project :"A1"},
                   {document_id :"LA040190-0178" ,topic_id :"302" , project :"A1"},
                   {document_id :"FT934-5418" ,topic_id :"303" , project :"A1"},
                   {document_id :"LA071090-0047" ,topic_id :"304" , project :"A1"}]

这是我的计划:

我想通过 document_id 字段更新数组中的项目。所以这是我的更新操作。

var query = {"document_id" : { $in:["FBIS3-50136","LA040190-0178","FT934-5418","LA071090-0047"]}};
Pools.collection.update(query, { $push : { "$ROOT" :  poolItems }  }, { upsert: true, multi : true}, callback);

错误:\'$ROOT\' 中的美元 ($) 前缀字段 \'$ROOT\' 对存储无效。

但是在每次尝试时,我都会遇到不同的错误,有没有办法使用猫鼬更新操作来更新项目? 谢谢

【问题讨论】:

标签: node.js mongodb mongoose upsert


【解决方案1】:

here 所述,批量更新插入实际上是不可能的,以及可能的解决方案。

但是,您可以考虑使用带有 promise 的每个 poolItems 或某些 async 方法(如 each)使用 upsert 操作的更简单方法。下面的代码应该可以工作:

var async = require('async');
var Pool = require('/path/to/pool.js');

var poolItems = [
{document_id :"FBIS3-50136" ,topic_id :"301" , project :"A1"},
{document_id :"LA040190-0178" ,topic_id :"302" , project :"A1"},
{document_id :"FT934-5418" ,topic_id :"303" , project :"A1"},
{document_id :"LA071090-0047" ,topic_id :"304" , project :"A1"}];

async.each(poolItems, function(poolItem, callback){
    Pool.findOneAndUpdate({document_id: poolItem.document_id}, poolItem, {upsert:true}, function(err, doc){
        if(err){
         return callback(err);
        }
        return callback();
    });
}, function(err){
    if(err){
        console.log(err);
    }
    else{
        console.log("All pool items have been upserted!")
    }
});

【讨论】:

  • 我是这么想的,但是关于性能,这个列表实际上相当大。您认为这仍然是一种好方法吗?
  • 我认为这是一种合理的方法。名单有多大?
  • 至少 40 项
  • 没什么。我想到了数百万:) 去吧。
  • 改变的方法是什么?通过 for 循环更新多少文档被认为太多?
猜你喜欢
  • 2019-07-09
  • 2015-02-19
  • 2018-01-02
  • 2015-10-20
  • 2020-04-20
  • 1970-01-01
  • 2018-09-04
相关资源
最近更新 更多