Sean McClory
Sean McClory

Reputation: 4283

Setting value of an array element in Mongoose using index

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?

Upvotes: 3

Views: 2968

Answers (2)

EnKrypt
EnKrypt

Reputation: 777

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';

Upvotes: 3

zs2020
zs2020

Reputation: 54524

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

Upvotes: 3

Related Questions