KLôN KLôN - 4 months ago 10
Javascript Question

Node.js : how to know if a value is in a collection of a MongoDB database?

It must be a very simple question, but I can't find a way to do it...

I have a very basic MongoDB collection of documents, which I can represent in JSON format like this :

myDatabase.myCollection = {
{hashkey: "hashkey1",
data: "someData"
},
{hashkey: "hashkey2",
data: "someData"
},
{hashkey: "hashkey3",
data: "someData"
}
}


Each hashkey value is unique.

Now, I want to write the following code in Node.js :

// I use npm mongodb, sounds good ?
var mongodb = require('mongodb');

// initiating connection to myDatabase...

var db = "my_database_I_just_connected_to";
var myCollection = db.collection('myCollection');

var newHashkey = "hashkeyX";

if ("newHashkey_is_already_in_myCollection") {
doSomething();
} else {
doSomethingElse();
}


I am looking for a way to get the boolean "newHashkey_is_already_in_myCollection". Using my example database :


  • if "hashkeyX" === "hashkey1" ------> true

  • if "hashkeyX" === "hashkey5" ------> false



I must be blind, but I can't find an immediate function for this purpose. I have tried many ways using selectors, counting returned documents, trying to understand cursors vs objects... Won't do. My initial thought was :

if (myCollection.findOne({hashkey: "hashkeyX"}) === null) {
doSomething();
} else {
doSomethingElse();
}


1) What is a good/best way to get such a boolean ?

2) [Optional :] Could you link me to some good explanations about such questions ?

Answer

findOne is an async operation, you must use callback and check that object is exists there:

myCollection.findOne({hashkey: "hashkeyX"}, function(err, obj) {
  if (err) {
    // TODO: process error
  }
  if (obj) {
    doSomething();
  } else {
    doSomethingElse();
  }