[英]mongoose query doesnt work in node.js but works in mongo shell
[英]MongoDB query working in Mongo Shell but not in Node.js?
我一直在使用MongoDB在Node.js服務器上工作。
每當我在Mongo Shell中使用此行時:
db.users.findOne({name:"john"},{password:true, _id:false}).password
如您所見,它工作正常( connor
是預期的答案)
但是,在Node.js中,使用適合於Node.js語法的同一行:
db.collection('users').findOne({name:"john"},{password:true, _id:false}).password
它只是返回undefined
我在本地和遠程服務器上嘗試了相同的代碼,並且得到了相同的答案。
我以為這可能是數據庫的連接錯誤,但是insertOne()
在Node.js中工作正常,所以我猜它不會是連接。
這是相關的代碼段:
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();
});
有什么建議嗎?
用於NodeJS的MongoDB驅動程序使用回調來處理查詢結果。 調用db.collection('users')。findOne({...})不會返回結果。 相反,它需要一個回調來處理結果:
// 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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.