简体   繁体   English

简单的数据库mongo查询出错了?

[英]Simple db mongo query gone wrong?

Hey I am trying to query the database (mongodb) from my index.js file then return the value from the query into a variable so I can then use that variable to show the persons information on the website. 嘿,我试图从index.js文件中查询数据库(mongodb),然后将查询中的值返回到变量中,以便随后可以使用该变量在网站上显示人员信息。 I currently have this code up but it is giving me problems. 我目前有此代码,但它给我带来了问题。 Trying to figure out how to query it the right way. 试图弄清楚如何以正确的方式查询它。 I am querying the email but I want to extract the first name based on an email query. 我正在查询电子邮件,但我想根据电子邮件查询提取名字。 I am using node.js and jade for my view engine. 我正在使用node.js和jade作为我的视图引擎。

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

var user = function (name) { 
    var name = db.users.find({ email: 'works@gmail.com' }).pretty();
    console.log(name); 
    return name;
};

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

It looks like you're using Mongoose, so what I'd suggest is that you use their querying functions which have worked well for me in the past. 看来您使用的是Mongoose,所以我建议您使用过去对我来说效果很好的查询功能。 It also helps to establish Mongoose models for your data stored in MongoDB. 它还有助于为存储在MongoDB中的数据建立Mongoose模型。

Try this (note: it is untested, but I pulled it from a functioning program): 尝试以下操作(注意:它未经测试,但是我从运行中的程序中将其拉出):

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: "someone@something.com"
    }, function(err, user) {
       if(err) {
           res.send(err);
       } else {
           console.log(user.firstName);
           res.render('index', {title: 'Weblio', user: user.firstName});
       }
    });
}

Nearly all IO in node is asynchronous which means that your find method isn't going to return the actual result but a promise or it is expecting a callback that it will call with the result. 节点中的几乎所有IO都是异步的,这意味着您的find方法不会返回实际结果,而是会返回一个Promise或期望将使用结果调用该回调。

Try this: 尝试这个:

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


exports.index = function(req, res) {
  db.users.find({ email: 'works@gmail.com' }, function(err, data){
    if(err){
      return req.send(500);
      }
    res.render('index', { title: 'Weblio', user: JSON.stringify(data)});
    });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM