Sujith S Manjavana
Sujith S Manjavana

Reputation: 1586

Mongoose insert or update array item

My model:

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 }
    )

I want to add an object to the words array if it doesn't exist otherwise update the value of repeat_count.

This is the word object I want to add: var word = { word : "hello" , repeat_count : "12" }

Is there any built-in function to do so?

Upvotes: 0

Views: 316

Answers (1)

daniel
daniel

Reputation: 89

first find your current object using id

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

then loop in your words array

   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();
    

Upvotes: 1

Related Questions