I'm not human
I'm not human

Reputation: 554

Get position with variable and then modify specific object in mongodb

How can I make this query use my variable instead of the hard coded 0?

let pos = 0;

{$set: {'answers.0.acknowledged': data}}

Upvotes: 1

Views: 53

Answers (2)

Akrion
Akrion

Reputation: 18515

Usually you choices are template literals, Array.join, String.concat etc:

let pos = 0;
let data = 'data';

let query = {$set: {[['answers.', pos,'.acknowledged'].join('')]: data}}

console.log(query);

With String.concat:

let pos = 0;
let data = 'data';
let query = {$set: {['answers.'.concat(pos,'.acknowledged')]: data}}
console.log(query);

Array.join, String.concat has a much better browsers support where template literals do not. If they were to be used @ the client side. In your case if you are using them at the back end you probably have nothing to worry about.

Upvotes: 2

mickl
mickl

Reputation: 49945

You can use ES6 String Interpolation and Computed Property Names to build the key for $set:

let pos = 0;
let data = 'some data';
let q = {$set: {[`answers.${pos}.acknowledged`]: data}}
console.log(q);

Upvotes: 2

Related Questions