简体   繁体   English

Mongoose,如果找到更新,则创建

[英]Mongoose,if found update else create

Ok so,lets say i have this array :好的,可以说我有这个数组:

const names = ["john","bill","mark"]

and this Model :这个模型:

const namesSchema = new Schema({
  name: String,
  frequency: Number,
});

I want to search each one of the array items by name,and if it exists,simply increment the frequency number by 1,else create the document with a name:array_item and frequency:1我想按名称搜索每个数组项,如果存在,只需将frequency数增加 1,否则创建name:array_itemfrequency:1的文档

I know i could just forEach the array,and do something like the following for each name :我知道我可以只为forEach数组,并为每个名称执行以下操作:

names.forEach(i => {
  const name_doc = await namesSchema.findOne({
    name: i,
  });
  if (name_doc) {
    name_doc.frequency += 1;
    name_doc.save()
  } else {
    const new_name_doc = new namesSchema({
      name: i,
      frequency: 1,
    });
    new_name_doc.save()
  }
})

but i was wondering if there is a more cohesive method where i could just pass the array,and the update function with an upsert option that does all this logic with a single call with no iterations但我想知道是否有一种更具凝聚力的方法,我可以只传递数组,以及带有 upsert 选项的更新函数,它通过一次调用完成所有这些逻辑,无需迭代

This might help you.这可能会帮助你。

I start with the collection我从收藏开始

[
    { "name": "mark" },
    { "name": "bill" },
    { "name": "john" }
]

and use this query to addnew docuemnt or increte frequence by name并使用此查询按名称添加新文档或增加频率

db.collection.update({name:'mark'},{$inc:{"frequence":1}},{upsert:true})

Edit编辑

or pass the array to query或将数组传递给查询

const names = ["john", "bill", "mark"]

var updates= names.map(function(item) {
    return {
        "updateOne": {
            "filter": { name: item },
            "update": { $inc: { "frequence": 1 } },
            "upsert": true
        }
    };
});

db.collection.bulkWrite(updates, {})

or或者

const names = ["john", "bill", "mark"]
    
names.map(function(item){
    db.collection.update({ name: item }, { $inc: { "frequence": 1 } }, { upsert: true })
}) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM