Achyut Jagini
Achyut Jagini

Reputation: 73

Mongodb find not printing json data

In the code I am trying to find all documents with code UE19CS204.But in the console.log a big message is printed not the JSON data.The findOne() is working but not find(). I don’t know what change to do to find all documents with code UE19CS204.

var MongoClient = require(‘mongodb’).MongoClient;
var url = “mongodb://localhost:27017/”;
MongoClient.connect(url, { useUnifiedTopology: true } ,function(err, db) {
if (err) throw err;
var dbo = db.db(“pes”);

dbo.collection(“course”).find({“code”:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);

});
dbo.collection(“course”).findOne({code:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});

});

Upvotes: 0

Views: 272

Answers (1)

norym
norym

Reputation: 707

The method find() creates a cursor for a query that can be used to iterate over results from MongoDB, see here. Use toArray(), you can finde the documentation here.

dbo.collection(“course”).find({“code”:“UE19CS204”}).toArray(function(err, docs) {
  if (err) {
    throw err;
  }
  console.log(docs);
})

Full example:

const MongoClient = require('mongodb').MongoClient;
 
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'pes';
// Collection Name
const collectionName = 'course';
// Filter
const filter = { 'code': 'UE19CS204' }
 
// Use connect method to connect to the server
MongoClient.connect(url, { useUnifiedTopology: true }, function(err, client) {
  if (err) {
    throw err;
  }
  client.db(dbName).collection(collectionName).find(filter).toArray(function(err, docs) {
      if (err) {
        throw err;
      }
      console.log(docs);
    })
  client.close();
});

Upvotes: 1

Related Questions