3

I am trying to update an element at a specific index in a mongodb array with mongoose.

db.Comment.findOneAndUpdate(
    {_id: '51fc9c329e87bf0000000001'},
    {$set: { 'body.0' : 'Comment Body'}}).exec(...);

This works fine, however, when I use a variable to set the index it doesn't seem to work. Does anyone know why?

    var indexString = "'body.0'";

    db.Comment.findOneAndUpdate(
        {_id: '51fc9c329e87bf0000000001'},
        {$set: { indexString : 'Comment Body'}}).exec(...);

And how would I get this working so that I can set the index as needed?

2 Answers 2

3

Use object instead:

var myIndex = { 'body.0' : 'Comment Body'};
var myIndex1 = { 'body.1' : 'xxx'};

db.Comment.findOneAndUpdate(
    {_id: '51fc9c329e87bf0000000001'},
    {$set: myIndex}).exec(...);

db.Comment.findOneAndUpdate(
    {_id: '51fc9c329e87bf0000000001'},
    {$set: myIndex1}).exec(...);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that. To build a bit further - var bodyIndex = {}; then bodyIndex['body.' + index] = 'Comment Body'; then passing that into the mongoose query solved it for me.
3

For anyone who stumbles upon this question later, the currently accepted answer does not address the actual issue in the code, which is that the variable used to set the index has been quoted twice as such :

var indexString = "'body.0'";

It is for this reason that the first query works (quoted just once), and the second does not. Changing the above line to this will fix this issue :

var indexString = 'body.0';

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.