illcrx
illcrx

Reputation: 814

How to retrieve items inside of the array instead of the array itself in javascript

My data comes from the user and gets stored as an object, that object needs to go into Mongo after some massaging on the server side. I am using Mongoose and using the $push {item} syntax to insert an item into my DB.

My Mongoose Model has photos: [] as the syntax, just a simple array. Inside of that array I need the photos uploaded. But if the users uploads at different times my array could end up with an array of arrays, and I just need one simple array with multiple objects.

Here is my route:

const testMedia = async (req, res) => {
  //loop through the res.locals.ids and save each as their own photo in the event
  let events = [];
  let photosArray =
  let owner = {id: req.user._id};
  const promises =  await res.locals.ids.map((photoLink) => {
     events.push({link: photoLink.link,
     dateUploaded: new Date(Date.now()).toLocaleString(),
     eventID: req.body.eventId,
     owner: owner
     })
  });
  await Event.findByIdAndUpdate(
      req.body.eventId,
      { $push: {
        photos: events
      }},
      { save: true, upsert: true, new: true },
      (err) => {
        if (err){
          console.log("Error in testMedia  ||  " + err);
          res.sendStatus(300);
        }
      }
    );

  await Promise.all(promises);
  res.render("eventDisplay", { events: event });
  res.end();
};

The problem that I am running into is that if I push the items into events I will be pushing an array of objects when I need just the objects themselves, so either I have to make one database call per object to insert, which seems like a waste of resources, or I need to find a way to insert all of the objects without wrapping them in an array.

For some reason I can't figure this out. Any ideas?

Upvotes: 0

Views: 60

Answers (1)

Sebastian Olsen
Sebastian Olsen

Reputation: 10888

According to the Mongo docs, you can use $each

.findByIdAndUpdate(req.body.eventId, {
  $push: {
    photos: { $each: events }
  }
})

This will push multiple items into your array.

Upvotes: 1

Related Questions