MongoDB Node.js every method

I have an array of data that I will store in the database. When I search if the data already exists, each () will be called twice, even if I use limit (1). I have no idea what's going on here ...

collection.find({
    month: 'april'
}).limit(1).count(function(err, result){
    console.log('counter', result);
});

collection.find({
    month: 'april'
}).limit(1).each(function(err, result){
    console.log('each', result);
});

collection.find({
    month: 'april'
}).limit(1).toArray(function(err, result){
    console.log('toArray', result);
});

At this time, there is an exact 1 dataset for the month of April, which is already stored in the collection. The above queries will generate this output:

count 1
each {...}
each null
toArray {...}

In the mongo shell, I checked the count () and forEach () methods. Everything works as expected. Is this a problem with the driver? Am I doing something wrong?

+4
source share
1 answer

. , null, , . examples:

// Find returns a Cursor, which is Enumerable. You can iterate:
collection.find().each(function(err, item) {
  if(item != null) console.dir(item);
});

, each:

if(this.items.length > 0) {
  // Trampoline all the entries
  while(fn = loop(self, callback)) fn(self, callback);
  // Call each again
  self.each(callback);
} else {
  self.nextObject(function(err, item) {

    if(err) {
      self.state = Cursor.CLOSED;
      return callback(utils.toError(err), item);
    }

>>  if(item == null) return callback(null, null);  <<
    callback(null, item);
    self.each(callback);
  })
}

each loop, (var doc = self.items.shift();). this.items.length 0, else. else . , nextObject null (item null), if(item == null) return callback(null, null);. , null, null, .

, MongoDB cursor. , find(), , . MongoDB . " 101 , 1 ". , this.items.length , , , . , this.items.length 0, MongoDB . , , null.

, . , limit(100000) , MongoDB 100000 . . MongoDB . , 101 . this.items.length 101, , . , ( 102-), MongoDB . , , null .

nextObject() , null, MongoDB.

+1
source

Source: https://habr.com/ru/post/1539993/


All Articles