1

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}, ...
4
  • are you trying to pull an array from database and then update it ? Commented Sep 26, 2018 at 13:58
  • the array is empty, I am trying to add a new object into it Commented Sep 26, 2018 at 14:02
  • where are you getting the array from ? Commented Sep 26, 2018 at 14:09
  • I declared it in the schema, so in the DB in each document there is this empty array Commented Sep 26, 2018 at 14:11

1 Answer 1

2

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();
        })
    }
})
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.