简体   繁体   中英

MongoDB query working in Mongo Shell but not in Node.js?

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?

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);
  });

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