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?