0

I have a large array that comes in from an API that I'd like to store straight into MongoDB.

Model.create(largeArray) ... // many documents created

The problem is, I have one additional key:value pair that I need to set for all documents in that array. It's a user id, and many documents are created for a given user once per API call. So for a given Model.create call, the user id is the same for every doc in the array.

Without mapping over the array, is there an efficient way of adding a field with a consistent value? Something like Model.create(myLargeArray, {userId: someUserId}) would be ideal, but I know this isn't the case with the Mongoose API.

function addDocsForUser(largeArray, someUserId) {

  // each element of largeArray needs to have `userId: someUserId` added to it

  return Model.create(largeArray)
}
Shruggie
  • 869
  • 6
  • 20
  • _"Without mapping over the array"_. Why not? – robertklep Oct 14 '17 at 09:28
  • @robertklep Mongoose is already mapping over it for the `.save` calls, and given the scale, I'd like to optimize wherever possible. Maybe with a custom create method. In general, I've been working to minimize any preprocessing of the API's responses, and this would get it down to zero ;) – Shruggie Oct 14 '17 at 09:40
  • Its not possible. You need to [map over the array to add userId](https://stackoverflow.com/a/39827195/1022914) before executing `Model.create()`. – Mikey Oct 14 '17 at 17:34
  • @Mikey it's plausible that mapping can be deferred to when Mongoose ends up mapping over the whole thing anyway. For example, if I had a default value, or a setter on my Schema, it would be added at that stage. The API of `Model.create()`, of course, isn't sufficient for what I'm asking. – Shruggie Oct 14 '17 at 20:39

0 Answers0