0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! Wow so simple. I'll go through the docs and see how I missed it.

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.