Wednesday, 12 April 2017

Mongodb generates new value with findOne function

I'm building an application in node.js and I have a mongodb as database. I'm trying to get a value out depending on some parameters, but each time I get a value, the document is updated, so that the data in the db is not persistent.

The code I'm using:

The connect function

function connect(callback) {
MongoClient.connect(sDbUrl, function(err, db) {
    if (err == null) {
        dbProjectStay = db;
        callback(null, db);
        bIsConnected = true;
        return true;
     }
  });
}

The function that pulls data:

dbcontroller.checkApiKey = function(sKey, callback) {
connect(function(err, db) {
    var users = db.collection("users");
    users.findOne({
            apikey: sKey
        },
        function(err, doc) {
            console.log(doc);
            if (doc != null) {
                callback(null, {
                    status: true
                });
            } else {
                callback(null, {
                    status: false
                });
            }
        });
   });
}

I get the following output from the console.log:

{ _id: 58ee501969ff7c49d6d830eb,
  apikey: 'cc35012b458119210f40d109224f7693',
  name: 'XXXXXXXXXXX',
  email: 'XXXXXXXXXX',
  user_name: 'XXXXXX' }

Then I try to run it again, and the value of the apikey is changed:

{ _id: 58ee501969ff7c49d6d830eb,
  apikey: 'acd0149d30702070a2d5c6f9f07f173d',
  name: 'XXXXXXXXXXX',
  email: 'XXXXXXXXXX',
  user_name: 'XXXXXX' }

When I run db.users.find({apikey:"acd0149d30702070a2d5c6f9f07f173d"}).pretty(); in the shell, I get:

{ _id: 58ee501969ff7c49d6d830eb,
  apikey: 'acd0149d30702070a2d5c6f9f07f173d',
  name: 'XXXXXXXXXXX',
  email: 'XXXXXXXXXX',
  user_name: 'XXXXXX' }

There is no validation on the collection as of right now, and I know that the check for if the key is present should be changed.

What am I doing wrong ?



via Lasse

No comments:

Post a Comment