Update array specific positions using mongodb with or without Mongoose!

Asked

Viewed 23 times

0

I have the following situation!

const meuModel = new mongoose.Schema({

  nome: { type: String, required: [true, 'Nome'] },
  
  links:{type : Array,},
}) 

Links is an array of objects!

links [{url:link, clicks:0},{url:link1, clicks:0},{url:Link2, clicks:0}]

I need to do specific update. Without ever changing the clicks, nor touching them!

links [{url:link, clicks:4},{url:novoLink, clicks:0},{url:link2, clicks:5},{url:novoLink2, clicks:0}]

i want to allow the user to modify the Links as you want. But clicks will always be via system.

My problem is saving me this in the Amazon!

teste = await MeuModel.findOneAndUpdate({
          _id
        },{$inc: {
          "links.0.url":'novolink', 
          "links.1.url": 'linkantigo', 
          "links.2.url": 'novo link se for novo',   
      }}

This is not working! Because you want to change a position, only when you live on the front! If the user has changed 3 links, they must be saved!

"$set" does not accept that I go through the array to modify only where necessary! "$set" only allows change of 1 specific position

await meuModel.findOneAndUpdate({
          _id
        },{ 
          "$set": {[`links.$[outer].url`]: 'novoLink'} 
        },
        { 
          "arrayFilters": [{ "outer.url":'antigoLink'}]
        })

$set with arrayFilters only accepts one condition for many or only 1.

I want to be able to have the whole array saved at once, with modifications only of the links, if they exist!

1 answer

-1

I got it using the save command()

My logic is: Data comes from the front modified or not! I call my model by ID.

const links = await meuModel.findOne({
    _id
   })

   links.links.forEach((v,i) =>{
  
 
   if(v.url !== front.links[i]?.url){
     

   links.links[i].url = front.links[i]?.url
  
   }

 })
 Links.markModified('links')
 const save =  await links.save()

use foreach to compare front and back data

foreach compares each position of the front array with each position of the array that came from bank

if any link is different from the old one, the new one is added at the same position!

links.links[Posicao].url = dado_do_front na mesma posição 

I do it in every position Note to Mongo that I changed the array

Links.markModified('links')

const save =  await links.save()

This logic works perfectly! Links are changed and clicks never moved

But I don’t know if it’s the best logic!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.