prcbass
prcbass

Reputation: 339

How to search mongodb collection entry attributes

I have a collection in my mongo database by the name "user collection". The collection holds entries with one attribute by the name "DBinstaID".

{ "_id" : ObjectId("5595f6be3eaf90ae2d759cc6"), "DBinstaID" : "280430135" }

I am trying to determine whether a new entry has the same DBinstaID value, and if so increase the count of "idCount". The following code is used in my index.js routing file for node.js/express.

var collection = db.get('usercollection');

var checkDuplicate = collection.find({$where: function(){this.DBinstaID === instaID}});

  console.log("DUPLICATE STATUS: " + checkDuplicate);

  if(!(checkDuplicate)){
    idCount++;
  }

However, the checkDuplicate variable is simply set to [object Object] instead of the boolean true or false. How can I search the collection and return a boolean?

Thank you in advance for the help.

Upvotes: 0

Views: 666

Answers (1)

Antoine
Antoine

Reputation: 4029

The collection.find() method is asynchronous, this means you can't get the results right away, and you need to handle anything dependant on these results directly in the callback.

I strongly advise you to have a good read of mongoosejs's docs (at least the code examples), and to take a look at basics of asynchronous programming in node.js (a google search away).

You can use collection.findOne() to get only one result :

var collection = db.get('usercollection');

collection.findOne({DBinstaID: instaID}, function(err, user) {
    // don't forget to check for errors here, masked for clarity
    console.log("DUPLICATE STATUS: ", user);
    if(user) {
      idCount++;
    }

    // rest of the code
});

Upvotes: 4

Related Questions