2016-01-28 91 views
1

我一直在使用MongoDB來研究Node.js服務器。MongoDB查詢在Mongo Shell中工作,但不在Node.js中?

每當我用這條線在蒙戈外殼:

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

它工作正常as you can seeconnor是預期的答案)

然而,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(); 
}); 

有什麼建議?

+0

您應該使用回調 – styopdev

回答

2

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

它只是返回'類型錯誤:無法讀取null' –

+0

的特性「密碼」這意味着它沒有發現這樣的用戶名爲「約翰」。你需要取消註釋'db.collection('users')。insertOne({...})'查詢。 – gnerkus

+0

如我所說,仍然顯示相同的錯誤,該文件位於數據庫中,Mongo Shell可以讀取它。 –

相關問題