使用节点从mongodb集合中获取特定数据

时间:2023-02-10 02:31:13

He yall, I need some help with my node and MongoDB application.

他,我需要一些关于我的节点和MongoDB应用程序的帮助。

So I have a MongoDB database and im fetching the data using node.js with express.js. I fetch the data fine with my application, and I can even send it to my browser. But I want to render a template I have (shown below).

所以我有一个MongoDB数据库,我使用带有express.js的node.js来获取数据。我用我的应用程序获取数据很好,我甚至可以将它发送到我的浏览器。但我想渲染一个模板(如下所示)。

  <!DOCTYPE html>
<html>
  <head>
    <title>{{ title }}</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>{{ title }}</h1>
    <p>Hello my name is {{ name }}, and my email is {{ email }}</p>
  </body>
</html>

With this model

有了这个模型

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

var usersSchema = new Schema({
  name: String,
  email: String
});

mongoose.model('emaildata', usersSchema);

But when i try and do this with this script

但是,当我尝试使用此脚本执行此操作时

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var fs = require('fs');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);

// MongoDb Server
mongoose.connect('mongodb://127.0.0.1/emailApp');

// Load all files in models folder. Importing models and schemas
fs.readdirSync(__dirname + '/models').forEach(function(filename) {
  if (~filename.indexOf('.js')) require(__dirname + '/models/' + filename)
});

app.get('/data', function(req, res) {
  mongoose.model('emaildata').find(function(err, emaildata) {
    res.send(emaildata)
    // res.render('email', { title: 'Emails', email: emaildata.email, name: emaildata.name });
  });
});




// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

It doesn't render anything. I believe the problem is 1. im not using the right syntax to identify the specific data in the object, like name or email. I try and do this about half way down my script by the app.get('/data'.... 2. I'm not importing the object correctly, so when I try and use the data to render my template, there is nothing.

它没有渲染任何东西。我相信问题是1.我没有使用正确的语法来识别对象中的特定数据,如名称或电子邮件。我尝试通过app.get('/ data'....我的脚本的一半左右执行此操作.2。我没有正确导入对象,所以当我尝试使用数据渲染我的模板时,那里没什么。

Thanks a bunch!

谢谢你!

2 个解决方案

#1


0  

First, res.send will not use your template file.

首先,res.send不会使用您的模板文件。

I assume that your template file's name is "email", so use res.render('email', {information : emaildata}) and in your template file, use {{ information.name}} and {{ information.email }} to render them.(I haven't used hjs, so there may be some syntax error.)

我假设您的模板文件的名称是“email”,因此请使用res.render('email',{information:emaildata})并在模板文件中使用{{information.name}}和{{information.email}}渲染它们。(我没有使用过hjs,所以可能会出现一些语法错误。)

#2


0  

First of all,

首先,

Import the Modal schema

导入Modal架构

var mydataSchema = require('.<directory>/<yourmodalname>');

Then if you already have some data in your database, get that also fetched by updating this into your modal

然后,如果您的数据库中已有一些数据,那么通过将其更新到您的模态中来获取该数据

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

var usersSchema = new Schema({
  name: String,
  email: String
}, {collection : '<tableName>' });

mongoose.model('emaildata', usersSchema);

Then get all the data:

然后获取所有数据:

First declare the router

首先声明路由器

var router = express.Router();  

get the data

得到数据

router.route('/userData')
 .get(function(req, res) {
        mydataSchema.find(function(err, mydataSchema ) {
            if (err)
                res.send(err);

            res.json(mydataSchema );
        });
    });

#1


0  

First, res.send will not use your template file.

首先,res.send不会使用您的模板文件。

I assume that your template file's name is "email", so use res.render('email', {information : emaildata}) and in your template file, use {{ information.name}} and {{ information.email }} to render them.(I haven't used hjs, so there may be some syntax error.)

我假设您的模板文件的名称是“email”,因此请使用res.render('email',{information:emaildata})并在模板文件中使用{{information.name}}和{{information.email}}渲染它们。(我没有使用过hjs,所以可能会出现一些语法错误。)

#2


0  

First of all,

首先,

Import the Modal schema

导入Modal架构

var mydataSchema = require('.<directory>/<yourmodalname>');

Then if you already have some data in your database, get that also fetched by updating this into your modal

然后,如果您的数据库中已有一些数据,那么通过将其更新到您的模态中来获取该数据

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

var usersSchema = new Schema({
  name: String,
  email: String
}, {collection : '<tableName>' });

mongoose.model('emaildata', usersSchema);

Then get all the data:

然后获取所有数据:

First declare the router

首先声明路由器

var router = express.Router();  

get the data

得到数据

router.route('/userData')
 .get(function(req, res) {
        mydataSchema.find(function(err, mydataSchema ) {
            if (err)
                res.send(err);

            res.json(mydataSchema );
        });
    });