2013-07-08 22 views
1

嘿我想从我的index.js文件中查询数据库(mongodb),然后将查询中的值返回到变量中,以便我可以使用该变量在网站上显示个人信息。我目前有这个代码,但它给我的问题。试图找出如何以正确的方式来查询它。我正在查询电子邮件,但我想根据电子邮件查询提取名字。我为我的视图引擎使用node.js和jade。简单的db mongo查询出错了吗?

var mongoose = require('mongoose') 
    , db = mongoose.createConnection('mongodb://localhost/test5'); 

var user = function (name) { 
    var name = db.users.find({ email: '[email protected]' }).pretty(); 
    console.log(name); 
    return name; 
}; 

exports.index = function(req, res) { 
    res.render('index', { title: 'Weblio', user: user}); 
}; 

回答

4

它看起来像你使用的是Mongoose,所以我建议你使用他们的查询函数,这些函数在过去对我来说效果很好。它也有助于为存储在MongoDB中的数据建立Mongoose模型。

试试这个(注:这是未经测试,但我把它从运作程序):

var mongoose = require('mongoose') 
    , Schema = mongoose.Schema; 

mongoose.connect('mongodb://localhost/test5'); 

var UserSchema = new Schema({ 
    email: { type: String, index: true }, 
    firstName: { type: String }, 
    lastName: { type: String } 
}); 

mongoose.model('User', UserSchema); 

var User = mongoose.model('User'); 

exports.index = function(req, res) { 
    User.findOne({ 
     email: "[email protected]" 
    }, function(err, user) { 
     if(err) { 
      res.send(err); 
     } else { 
      console.log(user.firstName); 
      res.render('index', {title: 'Weblio', user: user.firstName}); 
     } 
    }); 
} 
+0

感谢的是工作,是的,我有一个用户模型不知道如果我可以用它这样。做res.send(err)或req.send(500)更好吗? – Lion789

+0

您是否希望用户看到错误,取决于您。你可以对用户执行'res.send(500)',也许'console.log(err)'可以看到它。 – jrthib

+0

有道理,对于这种情况或人们通常采用的路线,最佳做法是什么? – Lion789

1

几乎所有IO在节点是异步的,这意味着你的查找方法是不会返回实际的结果,但一个承诺或它期待一个回调,它会调用的结果。

试试这个:

var mongoose = require('mongoose') 
    , db = mongoose.createConnection('mongodb://localhost/test5'); 


exports.index = function(req, res) { 
    db.users.find({ email: '[email protected]' }, function(err, data){ 
    if(err){ 
     return req.send(500); 
     } 
    res.render('index', { title: 'Weblio', user: JSON.stringify(data)}); 
    }); 
}; 
+0

findOne比找到的更好,这两个调用之间的区别是什么?假定您正在搜索的内容是唯一的,并且您只搜索一个用户? – Lion789

+0

'findOne'只是返回找到的第一个结果,而不是搜索整个集合。我相信你也可以使用普通的'find'查询来设置一个限制。在通过电子邮件地址进行搜索的情况下,它们很可能是独一无二的,因此返回它找到的第一个是有意义的。但它确实取决于你的数据集。 – jrthib

+0

还好,这是一个聪明的方式来查询数据库,每当你想拉起用户的个人资料在网页上?我最终试图做的是从登录的用户那里获取一个cookie,并使用该电子邮件查询他的信息并在用户配置文件页面上向他显示他的信息。我也在使用骨干,因此从骨干获取信息而不是像这样查询会更好。 – Lion789