如何在node.js中从mongodb获取用户信息 [英] How to get user info from mongodb in node.js
问题描述
对于mongo来说,这完全是陌生的,我已经检查了几个小时的示例,试图检查该集合中是否存在用户:
Totally new to mongo, I've been checking examples for hours, Trying to check if a user exists in this collection:
{ "name" : "chrispy", "pass" : "xxxx", "_id" : ObjectId("5221b29b69f9e9b11a000001") }
但是不能匹配名称并获得结果,我已经尝试了很多例子,也没有运气.
But cannot match name and get the results, i've tried numerous examples, and no luck.
在控制台中运行良好:
mongo main
> db.users.findOne({name : 'chrispy'})
{
"name" : "chrispy",
"pass" : "xxxx",
"_id" : ObjectId("5221b29b69f9e9b11a000001")
}
>
一旦我可以匹配名称,我将匹配密码.但甚至无法达到与用户名匹配的程度.帮助= 1000谢谢!
Once I can match the name, I'll match the password. but cant even get as far as matching the user name. Help = 1000 thankyou's!
var name = 'chrispy';
var pass = '';
console.log("About to check for name and pw");
Mongo.connect('mongodb://127.0.0.1:27017/main', function(err, db) {
if(err) throw err;
var collection = db.collection('users');
// does user exist
var doc = collection.findOne({name : name}, function(err,doc){
if(err) throw err;
if(doc)
console.log("1 Found: "+name+", pass="+doc.pass);
else
console.log("1 Not found: "+name);
});
if(doc)
console.log("2 Found: "+name+", pass="+doc.pass);
else
console.log("2 Not found: "+name);
db.close();
});
控制台输出:
About to check for name and pw
2 Not found: chrispy
它似乎并没有进入findOne()函数,但在findOn()函数外部,它还是会失败.
It doesn't even seem to be going in to the findOne() function, external to the findOn() function it fails anyway.
推荐答案
所以这是开始工作之前所做的更改,删除了var Doc =,并仅在触发findOne()中的函数之后关闭了db,否则它将关闭结果之前的数据库.
So here are the changes before it started to work, removed var Doc = , and closed the db only after function within findOne() is fired, else it closes the DB before the result.
var name = 'chrispy';
var pass = '';
console.log("About to check for name and pw");
Mongo.connect('mongodb://127.0.0.1:27017/main', function(err, db) {
if(err) throw err;
var collection = db.collection('users');
// does user exist
collection.findOne({name : name}, function(err,doc){
if(err) throw err;
if(doc)
console.log("Found: "+name+", pass="+doc.pass);
else
console.log("Not found: "+name);
db.close();
});
});
这篇关于如何在node.js中从mongodb获取用户信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!