【问题标题】:Mongoose insert or update array itemMongoose 插入或更新数组项
【发布时间】:2021-04-27 19:07:46
【问题描述】:

我的模特:

const userSchema = mongoose.Schema({
        _id: mongoose.Types.ObjectId,
        name: { type: String, required: true, maxlength: 32, trim: true },
        email: { type: String, required: true, trim: true, unique: true },
        words: [Object]
    }
    , { timestamps: true }
    )

如果 word 数组不存在,我想添加一个对象,否则更新 repeat_count 的值。

这是我要添加的词对象: var word = { word : "hello" , repeat_count : "12" }

有没有内置函数可以做到这一点?

【问题讨论】:

标签: node.js arrays mongoose


【解决方案1】:

首先使用 id 找到您当前的对象

 const findResponse = await this.{yourModel}.find(id);

然后在你的单词数组中循环

   const index = findResponse.words.findIndex(
    (data) => data.word === word.word
  );

 let newData = {}
 let newArray = findResponse.words
if(index) {
      newArray[index] = word 

   else {
    newArray.push(word)
  }

   newData ={
      ...findResponse,
     words : newArray
     
   }
  const UpdateOrInsertData= new this.{yourModel}(newData);
  let saveResponse = await UpdateOrInsertData.save();
    

【讨论】:

    猜你喜欢
    • 2019-07-09
    • 2015-10-20
    • 2020-12-17
    • 2012-09-10
    • 2018-06-16
    • 2018-12-09
    • 2020-12-12
    • 2022-01-07
    • 2020-09-13
    相关资源
    最近更新 更多