klonaway
klonaway

Reputation: 479

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 :

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 ?

Upvotes: 3

Views: 52

Answers (2)

Tsangares
Tsangares

Reputation: 825

If you could represent the data like this:

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

Then you could do something like this:

if (db.collection(newHashkey)) {
  doSomething();
} else {
  doSomethingElse();
}

Upvotes: 0

alexmac
alexmac

Reputation: 19617

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();
  }

Upvotes: 3

Related Questions