Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.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
Mongodb,如果存在则替换,否则创建新文档,_Mongodb_Mongoose - Fatal编程技术网

Mongodb,如果存在则替换,否则创建新文档,

Mongodb,如果存在则替换,否则创建新文档,,mongodb,mongoose,Mongodb,Mongoose,mongodb中是否有接受数组作为输入的内置函数,将每个as项添加为文档,如果文档已经存在,则基于唯一索引(见下文),然后替换文档 在我的模式中,我得到了这些索引,它们定义了计算的唯一性 calculationSchema.index( { insId: 1, year: 1, month: 1, day: 1 }, { unique: true } ); 创建函数 export const createCalculations = async (calcul

mongodb中是否有接受数组作为输入的内置函数,将每个as项添加为文档,如果文档已经存在,则基于唯一索引(见下文),然后替换文档

在我的模式中,我得到了这些索引,它们定义了
计算的唯一性

calculationSchema.index(

      { insId: 1, year: 1, month: 1, day: 1 },
      { unique: true }
    );
创建函数

export const createCalculations = async (calculations: ICalculation[]) => {
  try {
    const createdCalculations = await mongoose
      .model("calculation")
      .create(calculations); // Replace if it exist based on indexs above, otherwise create it
    return Promise.resolve(createdCalculations);
  } catch (err) {
    console.log(err);
    return Promise.reject(err);
  }
};

是的,它叫replaceOne with upsert。但这只适用于单个文档。我有一个包含数千个文档的数组。好吧,那么你需要编辑这个问题以包含所有相关信息?是的,有点不清楚。已更新。您可以将大容量写入与upsert一起使用。看见