简体   繁体   中英

Updating A Deeply nested Array of Objects inside a mongoose query

I am trying to update a mongoose document, But its a deeply nested array of objects and I am having trouble updating it using the spread operator. I have an array of image-links and I wanna iterate through the relationships array in the database and add an image to each relation. The code shows my approach, but the syntax is wrong. I have added a db image which shows where I wanna add the image variable.

 // Get Images
        const imagesData = await axios.get(
          "https://randomuser.me/api/?results=4&gender=male"
        );
        const images = [];
        imagesData.data.results.forEach((result) => {
          images.push(result.picture.large);
        });

        // Update Company
        for (let i = 0; i <= 3; i++) {
          const updateCompany = await Companies.findByIdAndUpdate(
            req.params.id,
            { relationships: [
              ...relationships, 
              relationships[i]: {
                ...relationships[i], 
                image: images[i]}
              ] },
            { new: true }
          ).exec();
        }

Also I am using a mongoose query inside a for loop. Is it the right way to do it. mognoDB

You should fetch the document that you want. Then treat the fetched object as a javascript object and add or update whatever you want then use .save() function provided by mongoose.

let result = await Companies.findById(id);
result = result.map((company)=>{
  update your object here
})

result.save()

The .save() function will take care of updating the object in the database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM