Shankar Ghimire
Shankar Ghimire

Reputation: 146

How to retrieve data from mongodb

I am unable to retrieve data from mongodb.

Problem is: the code Article.find({}); is not working to retrieve data from database.

I am using WebStorm IDE. I want to retrieve all the data from data base.

Please help me to find the error in my code.

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;

Upvotes: 2

Views: 273

Answers (2)

Cavdy
Cavdy

Reputation: 618

First lets bring in your model,

require('./models/article');

the create a variable for the model

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

Next to display your articles from db

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

I hope this helps

Upvotes: 0

arizafar
arizafar

Reputation: 3132

move database connection code into db.js and import same in 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;

then in article.js

const mongoose = require('mongoose');

require('../db');

Upvotes: 1

Related Questions