Explination for why map works but mongodb $each doesn't

37 Views Asked by At

Can someone please explain why one method of adding arrays to my database works and the other doesn't. Really lost as to what the difference is. I'm using aldeed/node-simple-schema and collection2.

Example: Schema

'topFiveSkills': { type: Array, optional: true },
'topFiveSkills.$': { type: String, optional: true }

Example: 'Working example'

topFiveSkills = ["One", "Two", "Three"]

this.state.topFiveSkills.map((skill) => {
  ProfileCandidate.update(this.state.profileCandidateCollectionId, {
    $push: { 'topFiveSkills': skill }
  });
})

Example: 'Doesn't work'

topFiveSkills = ["One", "Two", "Three"]

ProfileCandidate.update(this.state.profileCandidateCollectionId, {
  $push: { 'topFiveSkills': { $each: [topFiveSkills] }}
});
1

There are 1 best solutions below

3
Chris Visser On

From what I can see is that you apply a nested array on your $each example. Try below:

topFiveSkills = ["One", "Two", "Three"]

ProfileCandidate.update(this.state.profileCandidateCollectionId, {
  $push: { 
   'topFiveSkills': { 
     $each: topFiveSkills 
   }
  }
});

Note that I'm putting my object key/vals on a separate line. Its exactly for this reason, but ofcourse not a critical thing.