bradtraversy / meanauthapp

Complete MEAN stack app with authentication
242 stars 152 forks source link

Mongoose showing null object though collection exists in MongoDB #43

Open vedagirigopinath opened 6 years ago

vedagirigopinath commented 6 years ago

I added new collection(blog) in meanauth DB and to fetch blog data using express api and to project the data in front end. but I am facing issue.

I am new to express js. Please help me in this.

I try to fetch data from local mongodb using mongoose in my ExpressJS App. But couldn't fetch data.

I have tried to use mongoose and mongojs to retrive data from mongodb.

Even tried with passing right collection name in schema.

Here is my code.

using mongoose(blogs.js)

const mongoose = require('mongoose');
const config = require('../config/database');
const DataSchema = mongoose.Schema ({
        "title": { type: String },
    "Description": { type: String },
    "Rate": { type: Number }
 }, { collection : 'Datas' });

const Datas = module.exports = mongoose.model('Datas', DataSchema);
//const Datas = module.exports = mongoose.model('Datas', DataSchema, 
'Datas');

module.exports.getblogs = function(){
Data.find({}, (recs)=>{
    if(recs){
        console.log('Records found' + recs)
    }else{
        console.log('Records not found');
    }
}); 

using mongojs(blog.js)

var mongojs = require('mongojs');

  var db = mongojs('mongodb://localhost:27017/mydb', ['blogs']);

// On Connection
db.on('connect', function () {
console.log('Mongo JS database connected')
});
//On Error
db.on('error', function (err) {
console.log('Mongo JS database error', err)
});

module.exports.getBlogs = function(res) {
//var data = db.blogs.find();
db.blogs.find({}, (rec, res)=>{
if(rec){
  res.json(rec);
  console.log('Data '+ rec)
}else{
  console.log('No Data '+ rec)
}
});
}