Question

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.

Was it helpful?

Solution

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
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top