0

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?

2

1 Answer 1

1

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();
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.