Fralec Fralec - 19 days ago 5
Node.js Question

Mongodb query not working with string

I'm using the

mongodb
package on my Nodejs app. I try to remove an nested object. It work when I put a nested object. It does not work when I put the string into the condition and I don't understand why. Can someone help me?

That doesn't work:

var tmp = 'records.' + j + '.domains';
records.update({'email': '<removed>'}, {'$pull': {tmp: {'_id': req.params.dn}}});


That work:

records.update({'email': '<removed>'}, {'$pull': {'records.1.domain': {'_id': req.params.dn}}});

Answer

You should use the following syntax:

var tmp_key = 'records.' + j + '.domains';
var tmp_value = {'_id': req.params.dn};
var query = {};
query[tmp_key] = tmp_value;
records.update({'email': '<removed>'}, {'$pull': query});