e.T55
e.T55

Reputation: 465

Mongoose not displaying data from mongoDB

i created a mongodb with a name userInfo with collection name "info" in the terminal and i created a schema in models/user_info.js.And i am not getting any values from the database at all. my userInfo db has name,studentId,dept

My view engine is jade/pug I am trying to iterate and display the values from the database. I am not getting an error but its not displaying the values. Thanks for the help!

app.js

const express= require('express');
const path = require('path')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')

mongoose.connect('mongodb://localhost/userInfo')
let db = mongoose.connection;


db.on('error',(error) => console.log(error));
db.once('open',() => console.log('Connected to Mongodb'))

const app = express()

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

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


let UserInfo = require('./models/user_info')

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

app.get('/',(req,res) => {
    UserInfo.find({},function(err,info){
        if(err){
            console.log(err);
        }else{
            res.render('tabel',{
                title:'user report',
                info:info
            });
        }
    })
})

user_info.js //shema

let mongoose = require('mongoose');


//Userinfo Schema
let userInfoSchema = mongoose.Schema({
    name:{
        type:String,
        required:true
    },
    studentID:{
        type:String,
        required:true
    },
    dept:{
        type:String,
        required:true
    }
});

let UserInfo = module.exports = mongoose.model('UserInfo',userInfoSchema);

Upvotes: 0

Views: 1335

Answers (1)

Shams Nahid
Shams Nahid

Reputation: 6559

In your model, you are pointing the collection name UserInfo, but your data are in 'info' collection.

So, change the collection name explicitly in your model.

Your user_info.js (schema) should be,

let mongoose = require('mongoose');
let userInfoSchema = mongoose.Schema({
    name:{
        type:String,
        required:true
    },
    studentID:{
        type:String,
        required:true
    },
    dept:{
        type:String,
        required:true
    }
});

let UserInfo = module.exports = mongoose.model('UserInfo', userInfoSchema, 'info');

In the last line, I pass the third argument, to indicate the collection name to info.

Upvotes: 2

Related Questions