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)
}
4
  • "Without mapping over the array". Why not? Commented Oct 14, 2017 at 9: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 ;) Commented Oct 14, 2017 at 9:40
  • Its not possible. You need to map over the array to add userId before executing Model.create(). Commented Oct 14, 2017 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. Commented Oct 14, 2017 at 20:39

0

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.