jmfbot
jmfbot

Reputation: 189

How to add object to nested array in mongoose?

In essence what I am trying to do is something along the lines of FindByIdAndCreate, a method which does not exist in mongoose.

I have a schema as so:

const WordSchema = new Schema ({
    TargetWord: String,
    Translation: String, 
    ExampleSentences: [{            
        Number: Number, //increment somehow each time 
        Sentence: String, 
    }],
});

I have a form where the user can add example sentences of this target word, the route for which looks like this:

router.put("/word/:id/add", async(req, res) => {
    //get the new sentence from the field 
        var NewSentence = req.body.Sentence;

Now once I have this new sentence saved to the variable NewSentence I want to create a new object within the WordSchema.ExampleSentences array which contains the new sentences itself, and the number which should automatically increment.

I have fiddled around with FindByIdAndUpdate to no avail,this syntax does not work because it throws an error at the use of .

WordSchema.findByIdAndUpdate(req.params.id, {ExampleSentences.Sentence: NewSentence}, ...

Upvotes: 1

Views: 2041

Answers (1)

Paradise228
Paradise228

Reputation: 717

The only solution to increment your counter is to retrieve every document with a good old 'find' and create your new entry accordingly, since 'update' has no way to self reference a document during the process.

router.put("/word/:id/add", async(req, res) => {
    WordSchema.find({_id: req.body.id}, function(results) {
        if (results.length === 0) return res.json();

        const word = result[0];

        const NewExampleSentence = {
            Number: word.ExampleSentences.length, // if your counter start from 1, then add 1 
            Sentence: req.body.Sentence
        };

        word.ExampleSentences.push(NewExampleSentence);
        word.save(function(err) {
            if (err) {
                // handle error
            }
            return res.json();
        })
    }
})

Upvotes: 2

Related Questions