1
votes

I've been doing some research within these couple of days but got stuck while trying to test the codes that I got from the web.

var MongoClient = require('mongodb').MongoClient,
  format = require('util').format;

MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
  if (err) {
    throw err;
  } else {
    console.log("successfully connected to the database");
    db.collection('chat', function(err, collection) {
    
      collection.find({}, {
          tailable: true,
          awaitdata: true,
          numberOfRetries: -1
        })
        .sort({
          $natural: 1
        })
        .each(function(err, doc) {
          console.log(doc);
        })
    });


  }
  db.close();
});

And the error is: c:\Project\node_modules\mongodb\lib\mongo_client.js:406 throw err ^ Am I missing any external library/reference because the error says "Cannot read property 'find' of undefined".

mongodb version: "2.0.31"

3
In the inner callback, check err before accessing collection.Sirko
As Sirko said may be problem with the collection.Check for err there.Subburaj
It says: [MongoError: Tailable cursor doesn't support sorting]ChiSen
is the version of my mongodb is the problem?thanks :)ChiSen

3 Answers

5
votes

You check for a possible error in your first callback, but not the second one. Instead of

db.collection('chat', function(err, collection) {
    collection.find({}, {...

Try:

db.collection('chat', function(err, collection) {
    if (err) {
        throw err;
    } else {
        collection.find({}, {...

This won't make your code snippet do what you want, but it will let you find out what error is preventing it from working.

0
votes

You didnt export the collection module correctly....

If suppose your model class is collection.js,

then at the end of the class, it should be

module.exports = { Collection}

Final code will look like,

const mongoose = require('mongoose')

var Collection = mongoose.model('Collection', {
    a: {type: String},
    b: {type: String},
    c: {type: Number},
}

module.exports = { Collection}
0
votes

You can also do it like this:

collection.find((err, data) => {
    if (err) {
      console.log("An error: ", err);
    } else {
      console.log("My data", data);
    }
  });