简体   繁体   中英

Trying to query MongoDB through node.js but keep getting weird error

I keep getting an error in regards to querying MongoDB:

var MongoClient = require('mongodb').MongoClient;
//assert = require('assert');


// Connection URL 
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server 
 MongoClient.connect(url, function(err, db) {
//assert.equal(null, err);
if(err)
 throw err;
else{
console.log("Connected correctly to server");
var cursor = db.collection('documents').find({'_id':'01'});
cursor.forEach(function(err,doc) {
  if(err){
      throw err;
  } else{
      console.log(doc);
 }});
db.close();

}});

The error I am getting is this.

process.nextTick(function(){ throw err;});

[object Object]

Any help is appreciated! Thanks.

Hi if you use nextObject() instead of forEach, your code should do what you want.

            var MongoClient = require('mongodb').MongoClient;
    //assert = require('assert');
    // Connection URL 
    var url = 'mongodb://localhost:27017/myproject';
    // Use connect method to connect to the Server 
    MongoClient.connect(url, function(err, db) {
    //assert.equal(null, err);
    if(err)
    throw err;
    else{
    console.log("Connected correctly to server");
    var cursor = db.collection('documents').find({'_id':'01'});
    //CHANGE HERE
    //cursor.forEach(function(err,doc) {
    cursor.nextObject(function(err,doc) {
    if(err){
        throw err;
    } else{
        console.log(doc);
    }});
    db.close();

    }});  

UPDATE:

when you do forEach on cursor the callback gives you document as the first parameter. So your if was catching it and throwing it. That is why you are seeing that error to begin with. This is because the way node-mongodb-native driver behaves check this How can I use a cursor.forEach() in MongoDB using Node.js?

nextObject function will give you two parameters, error as the first and the doc as the second. https://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#nextobject

Your code isn't working because you're not providing the right callback(s) to cursor.forEach and because that method is async so that you're calling db.close() before you've actually fetched your docs.

However, because you're querying for a single doc, you can use findOne instead which eliminates the complexity of dealing with the cursor returned by find :

MongoClient.connect(url, function(err, db) {
  if(err)
    throw err;
  else {
    console.log("Connected correctly to server");
    db.collection('documents').findOne({'_id':'01'}, function(err, doc) {
      if(err){
        throw err;
      } else{
        console.log(doc);
      }
      db.close();
    });
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM