0

My code looks like this :

  router.put('/stories/:story', function(req,res,next){
  Story.findById(req.story._id, function(err, story) {
        if (err) {
            res.send(err);
        }

        story.scenarios.push(req.body); 
        story.save(function(err,story) {
            if (err) {
                res.send(err);
            }
            res.json(story);
        })

    });
});

The req.body contains an object with an image and an audio. I want to be able to update this array with new objects. How do I push new objects to story.scenario (who is null in the beginning).

Now I get an error : 'cannot read property push of null'

Somebody who knows the solution?

3
  • 2
    Just initialize story.scenarios to an empty array before calling the push() method on it. Commented Dec 16, 2016 at 2:19
  • 2
    story.scenarios = []; story.scenarios.push(req.body); Commented Dec 16, 2016 at 2:19
  • Can you show your Story Schema? Commented Dec 16, 2016 at 4:16

3 Answers 3

4

The story.scenarios is null at the very beginning so you need to initialize it as [] but you don't want to do it all the time since story.scenarios may already has data.

story.scenarios = story.scenarios || [];
story.scenarios.push(req.body); 
Sign up to request clarification or add additional context in comments.

Comments

2

i am assuming story in the parameter is an object and it has _id present it. But still there lies a problem in your code.

You cant just use req.story to access ths passed object. All such objects are accessed using req.params.

Change your code to this, and it should work.

Story.findById(req.params.story._id, function(err, story) {
...
});

Also, i am assuming, in your Story Schema you have declared scenarios as an array, and req.body matches the type you defined in the schema.

Comments

2

Just initialize story.scenarios to be an empty array. Then it calling the push() funciton.

ex

story.scenarios = []; story.scanarios.push(someData);

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.