1

The Situation

I have a MongoDB of the following data structure

teamName: (String)
data: (Array)
---date: (Timestamp)
---userResults: (Object)
------userHash: (StringHash)
------score: (String)
------comment: (String)

Here is a short example on PasteBin.


The Question

Given a specific teamName and date (within the team data array), I'd like to append a new row ({userHash: '', score: '', comment: ''}) into userResults array.

How can I update an array within a given document, after querying the parent node, and the parents parent node?


What I've tried so far

I've tried findOneAndUpdate. It inserted an entire new document, right from the root though.

TeamRecordSchema.findOneAndUpdate(
    {teamName: teamName, data: {date: today}}, 
    {$set:{teamName: teamName, data: {date: today, userResults: [userResponse]}}}, 
    {new: true, upsert: true}, 
    function(err, savedDoc){

       // Do stuff with err and savedDoc

});

I've tried save, and again it just creates an entire new document at the root level, within my db

const _userResponse = new TeamRecordSchema(teamUserResponse);
_userResponse.save((err, savedDoc) => {

    // Do stuff with err and savedDoc accordingly     

 });

I've also tried several variations based on the documentation, but I either get the same results, or an error.

2
  • 1
    This should work TeamRecordSchema.findOneAndUpdate( {teamName: teamName, 'data.date': today}}, {$push:{'data.$.userResults': {userHash: '', score: '', comment: ''}}}, {new: true, upsert: true}, function(err, savedDoc){ }); Commented Mar 2, 2018 at 23:26
  • @Veeram, legend!! Thanks so much, that works perfectly, and is exactly what I'd been trying to do for the last 12 hours! If you put it as an answer, I'll accept (if you'd like the rep) Commented Mar 2, 2018 at 23:55

1 Answer 1

1

You have to use $positional operator.

You include the field (date) from the data to locate the index of element and replace the placeholder($) with the found index from query part in the update part to push the element in userResults.

TeamRecordSchema.findOneAndUpdate( 
  {teamName: teamName, 'data.date': today}}, 
  {$push:{'data.$.userResults': {userHash: '', score: '', comment: ''}}}, 
  {new: true, upsert: true}, 
   function(err, savedDoc){ }
);
Sign up to request clarification or add additional context in comments.

Comments

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.