0

I'm trying to make short way for me. I want to create one function for all queries. For settings.amount, settings.balance etc..

exports.updateUsers = function ( user_id, where, what, pass )  {
    var _where = 'settings.'+where; //when I use it doesn't update
    user.findOneAndUpdate(
          {'user_id' : user_id}, 
          {_where : what }).exec(function(e,d){
            pass("ok")
          })
};

How can I achive my want? Are there any way?

Lazy
  • 1,807
  • 4
  • 29
  • 49

2 Answers2

2

{_where : what } treats _where as a String literal, which is equivalent to: {"_where":what}. Hence you don't get any updated results since there is no field such as _where. You need to assign it in the below way to get it working.

exports.updateUsers = function ( user_id, where, what, pass )  {
    var _where = 'settings.'+where; //when I use it doesn't update
    var update = {};
    update[_where] = what;
    user.findOneAndUpdate(
          {'user_id' : user_id}, 
          update).exec(function(e,d){
            pass("ok")
          })
};

update[_where] = what; resolves the value in the _where variable.

BatScream
  • 19,260
  • 4
  • 52
  • 68
  • Hi, I'm new to mongo, and could you give an example of how to update using this function? Thanks! I mean what should I need to use for where, what, and pass? Also, there are 2 things going to update in function right(.exec(function(e,d))? – rra Jul 04 '20 at 04:14
1

You need to use the $set operator. See MongoDB docs for examples.

So I think your functions could be written like this:

exports.updateUsers = function ( user_id, where, what, pass )  {
    var setQuery = { $set: {} };
    setQuery.$set['settings.'+where] = what;
    user.findOneAndUpdate(
          {'user_id' : user_id}, 
          setQuery).exec(function(e,d){
            pass("ok")
          })
};
Tug
  • 189
  • 10
  • Hi, I'm new to mongo, and could you give an example of how to update using this function? Thanks! I mean what should I need to use for where, what, and pass? Also, there are 2 things going to update in function right(.exec(function(e,d))? – rra Jul 06 '20 at 16:42