Nb_me Nb_me - 1 month ago 20
Node.js Question

Unable to read collection data in mongo/node

I am trying out mongoDB in nodeJs and am having trouble with the db collection file on the mongodb server. The server is setup as a window service so it is up and running. I got nodejs to connects to it when ran. I did the mock examples and it works (I think it is properly set up).

If I want to see the collection created in nodejs it shows them. If I go to the mongodb server database(data\db folder) I see a collection has been created. The problem is when I open another instance of cmd.exe enter mongodb and want to see what is in the collection db.collections-2 what returns is NaN.

I may be doing something wrong or there is a missing file I am not aware of. Could someone please advise me and explain why I am getting NaN.

The nodejs code is bellow.

var MongoClient=require('Mongodb').MongoClient,format = require('util').format;
var url = 'mongodb://localhost:27017/myproject';
console.log("connected to", url );
var user1 = {name: 'modulus admin', age: 42, roles: ['admin', 'moderator', 'user']};
var user2 = {name: 'modulus user', age: 22, roles: ['user']};
var user3 = {name: 'modulus super admin', age: 92, roles: ['super-admin', 'admin', 'moderator', 'user']};

collection.find({name: 'modulus user', roles: 'user'}).toArray(function(err, result) {
if (err) {
} else if (result.length) {
console.log('Found:', result);
} else {
console.log('No document(s) found with defined "find" criteria!');



Ok, there are a few things in your question that are unclear, let me try to clarify :

You won't be able to read the collection data directly in data/db, you must use the mongo shell.

In the mongo shell, which I assume is what you refer to by "open another instance of cmd.exe enter mongodb", try entering the following commands :

 use myproject 
show collections
db.mycollection.find({}) //replace 'mycollection' by the name of the collection

That will show you the first docs of the collection 'mycollection'.

However, in your node code, you don't seem to be defining the collection name? It should look like this :

 var collection = db.collection('mycollection')
 collection.find({name: 'modulus user', roles:  'user'}).toArray(...