0

I just installed the latest versions of node.js and MongoDB and a driver for node.js: MongoJS

Now I tried to find out (with good performance due a high load app) if a record exists in the database. I tried this query but all I get is an error:

var query = db.users.find({ nickname: 'test' }).limit(1);
console.log(query.size());
// or also
// console.log(query.length); 
// => undefinied

Error:

TypeError: Object [object Object] has no method 'size'

Via console.log(typeof query) I just get object.

If I just log query I get this:

{ _readableState:
    { highWaterMark: 16384,
      buffer: [],
      length: 0,
      pipes: null,
      pipesCount: 0,
      flowing: false,
      ended: false,
      endEmitted: false,
      reading: false,
      calledRead: false,
      sync: true,
      needReadable: false,
      emittedReadable: false,
      readableListening: false,
      objectMode: true,
      ranOut: false,
      awaitDrain: 0,
      readingMore: false,
      decoder: null }
  readable: true,
  domain: null,
  _events: {},
  _maxListeners: 10,
  _get: [Function] }

I get all the time this as result, even if the item exists or not.

Community
  • 1
  • 1
David
  • 560
  • 2
  • 10
  • 26
  • Where are you seeing a reference to a `size` method that you're expecting to be able to call? – JohnnyHK May 05 '13 at 13:53
  • http://stackoverflow.com/questions/8389811/how-to-query-mongodb-to-test-if-an-item-exists – David May 05 '13 at 13:56
  • the reason printing 'query' looks so strange is because query is a cursor, it's not actually any results. You can solve your problem by using findOne, or checking what query.hasNext() returns (false - no items matched). I guess node.js equivalent would be cursor.nextObject() returning null. – Asya Kamsky May 05 '13 at 17:02

1 Answers1

0

I don't see any mention of a size method in the current docs. Instead, while count would also work here, you could use findOne to do this:

db.users.findOne({ nickname: 'test' }, function(err, doc) {
    if (doc) {
        // At least one matching doc exists
    } else {
        // No match found
    }
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471