1

I have been working on a Node.js server, using MongoDB.

Whenever I use this line in Mongo Shell:

db.users.findOne({name:"john"},{password:true, _id:false}).password

it works fine as you can see (connor is the expected answer)

However, in Node.js, using the same line adapted to the Node.js syntax:

db.collection('users').findOne({name:"john"},{password:true, _id:false}).password

it just returns undefined

I tried the same code in both my local and my remote server and I get the same answer.

I thought it could be a connection error with the database but insertOne() works fine in Node.js so I guess it won't be the connection.

Here you are the related piece of code:

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var connection_string = 'mongodb://127.0.0.1:27017/grumpyworld';
if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD){
  connection_string = process.env.OPENSHIFT_MONGODB_DB_URL;
}


console.log("MongoDB connection_string: "+connection_string);

MongoClient.connect(connection_string, function(err, db) {
  console.log("Connected to DB");
  //This line is commented so I don't insert a file each time I try the code
  //db.collection("users").insertOne({"name":"john", "password":"connor"});

  var pass = db.collection('users').findOne({name:"john"},{password:true, _id:false}).password;
  console.log(pass);


  db.close();
});

Any advice?

1
  • You should use callback Commented Jan 28, 2016 at 17:38

1 Answer 1

4

The MongoDB driver for NodeJS uses callbacks to process the results of queries. The call to db.collection('users').findOne({...}) does not return a result. Instead, it requires a callback to process the result:

// Pass a callback as an argument to the query.
db.collection('users')
  .findOne({name:"john"}, { fields: { password: true, _id: false } }, function(err, user) {
    console.log(user.password);
  });
Sign up to request clarification or add additional context in comments.

5 Comments

It just returns TypeError: Cannot read property 'password' of null
This means it found no such user with the name "john". You'll need to uncomment the db.collection('users').insertOne({...}) query.
Still showing the same error, as I said, the file is in the database, Mongo Shell can read it.
I've updated the answer with the part the was missed out of the query.
Still getting the same error: TypeError: Cannot read property 'password' of null :\

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.