如何从mongodb检索数据

时间:2019-01-16 07:35:17

标签: node.js mongodb express

我无法从mongodb检索数据。

问题是:代码Article.find({});无法从数据库中检索数据。

我正在使用WebStrom IDE。我想从数据库中检索所有数据。

我将代码发布在下面,请帮助我查找代码中的错误

谢谢。

database.js

module.exports = {
    database:'mongodb://localhost:27017/shopping_site',
}

models / article.js

let mongoose = require('mongoose');

// Article Schema
let articleSchema = mongoose.Schema({
    title:{
        type: String,
        required: true
    },
    author:{
        type: String,
        required: true
    },
    body:{
        type: String,
        required: true
    }
});

let Article = module.exports = mongoose.model('Article', articleSchema);

index.pug

extends layout

block content
  h1 #{title}
  ul.list-group
    each article, i in articles
      li.list-group-item= article.title

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var config = require('./config/database');
var bodyParser = require('body-parser');

var app = express();

// Bring in Models
let Article = require('./models/article');

//database connectionkjvhgc
mongoose.connect(config.database);
let db = mongoose.connection;

// Check connection
db.once('open', function(){
  console.log('Connected to MongoDB');
});

// Check for DB errors
db.on('error', function(err){
  console.log(err);
});

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

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Home Route
app.get('/', function(req, res){
  Article.find({}, function(err, articles){
    if(err){
      console.log(err);
    } else {
      res.render('index', {
        title:'Articles',
        articles: articles
      });
    }
  });
});

//set routes


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

//body-parser
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

2 个答案:

答案 0 :(得分:0)

将数据库连接代码移动到db.js中,并将其导入article.js

db.js

let uristring = <your connection string or import database.js>;

mongoose.connect(uristring);

// When successfully connected
mongoose.connection.on('connected', function() {
  console.log('Mongoose connection open to cluster');
});

// If the connection throws an error
mongoose.connection.on('error', function(err) {
  console.log('Mongoose connection error: ' + err);
});

// When the connection is disconnected
mongoose.connection.on('disconnected', function() {
  console.log('Mongoose connection disconnected');
});

// When the connection is open
mongoose.connection.on('open', function() {
  console.log('Mongoose connection is open');
});
module.exports = mongoose;

然后在article.js中

const mongoose = require('mongoose');

require('../ db');

答案 1 :(得分:0)

首先,请引入您的模型

require('./models/article');

为模型创建变量

const Article = mongoose.model('Article');

下一步显示数据库中的文章

app.get('/', (req, res) => {
    Article.find({}).then(Article => {
        res.render('index', {Article:Article});
    }).catch(err => console.log(err));
});

我希望这对您有帮助