rra
rra

Reputation: 809

MongoDB function and how to call it?

I'm new to MongoDB and I found this function on the web. it's going to work for my 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
    var update = {};
    update[_where] = what;
    user.findOneAndUpdate(
          {'user_id' : user_id}, 
          update).exec(function(e,d){
            pass("ok")
          })
};

Could anyone explain to me how can I call this query to update balance or amount?

Could anyone give me an example of updating something?

Upvotes: 0

Views: 55

Answers (1)

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

You can use it like this:

const { updateUsers } = require('./pathToFile.js'); // add the correct path;
// assuming you want to update the balance of a user to 69
updateUsers('some id', 'balance', 69, (result) => { 
 if(result === 'ok') {
  // do something
 } else if(result === 'bad') {
  // you have an error
 }
})

I would also change updateUsers to handle errors:

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 (error, d) {
            if (!error) {
                pass('ok');
            } else {
                pass('bad')
            }
        })
};

Upvotes: 1

Related Questions