MissingSchemaError: Schema hasn't been registered for model "Blog" - mongodb

I am getting above error which I am stuck I am a beginner of mongodb, expressjs
My Index.js:
const mongoose= require('mongoose')
let modelspath ='./models'
fs.readdirSync(modelspath).forEach(function(file){
if(~file.indexOf('.js'))
console.log(file)
require(modelspath +'/' + file) //if block checks weather file ending with .js ext
})
my controller file
const BlogModel = mongoose.model('Blog')
let testRoute = (req, res) =>
{
console.log(req.params)
res.send(req.params)
}
my model.blog.js file
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
let blogSchema =new Schema(
{
blogId :{
type: string,
unique:true
},
mongoose.model('Blog',blogSchema);
my routing file
const express =require('express')
//here we can find routees logic path
const control =require('./../controllers/controller')
let setRouter =(app) =>{
//here we are getting our logics and assigning for a Http verbs (get,post,put,del)
app.get('/test/route/:param1/:param2',control.testRoute)
app.get('/example',control.example)
// app.post('/hello', control.postmethod)
}
module.exports={
setRouter:setRouter
}
Can anyone help me out of this error

Related

i keep get TypeError x is not constructor

i have model with mongoose
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CampgroundSchema = new Schema({
title:String,
price:Number,
description:String,
location:String
});
module.export = mongoose.model('Campground', CampgroundSchema)
i save it
i import to variable
const Campground = require('campground');
i want to get data on browser so :
app.get('/makecampground', async (req, res) => {
const camp = new Campground ({title:"Corn Field", description:"We can BBQ there"})
await camp.save();
res.send(camp)
})
but when i go to browser 'localhost3000/makecampground' my terminal just say
Campground is not a constructor
so i want to that Campground data show on my database

MERN stack : Express api returning empty data , but the data is already present in mongodb

I am new to the MERN stack, and I have been trying to access my collections in MongoDB.
Here is the code for the router, view bookings:
/*This is router file*/
var mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser')
let book = require('../models/BookTravel');
const router = require('express').Router()
router.use(express.json())
router.route('/').get((req, res) => {
// Company.aggregate({companyId})
book.find()
.then((result) => {
console.log(result)
return res.status(200).json(result)
})
})
module.exports = router;
/*
* this is for model
*/
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const TravelSchema = new Schema({
firstname:{
type: String,
required: true
},
bookingId:{
type: String,
required: true
},
lastname:{
type: String,
required: true
},
startcity:{
type: String,
required: true
}
})
const travel = mongoose.model('travel', TravelSchema)
module.exports = travel;
////in app.js file
const viewBookings = require('./routes/viewBookings');
app.use('/viewBookings', viewBookings)
The postman is also giving empty result.
What am I missing out ? Is it not possible to access the already existing collection with this method ?
You are missing some code in the router file.
for example! If you want to get data from a database
you can simply use like below this
.......
router.get("/",async (req,res)=>
{
try{
const result = await book.find();
res.status(200).json({"message" : result})
}
catch(error)
{
console.log(error)
}
})
......

Import CSV file data into MongoDB using mongoose

I am building a full-stack application using MERN(MongoDB, Express, React, Node.js).
I have a .CSV file that I uploaded to MongoDB. However I can't get my routes to return any data.
I can see the database collection on my MongoDB cluster, But it's not showing up in my mongo shell.
My thought process is that's why I can't get my routes to work. How can I fix that?
sample .csv file data
Date,Client,Project,Project Code,Hours,Billable?,First Name,Last Name,Billable Rate
,,,,,,,,
4/3/17,Anil,Ethereum,RD001,3.84,No,Robert,Powell,0
4/3/17,Olith,Pharos,DV002,7.69,Yes,Hubert,Green,80
4/3/17,Olith,Pharos,DV002,4.46,Yes,Bradley,Hale,80
4/3/17,Olith,Pharos,DV002,7.57,Yes,Rudy,Parker,80
4/3/17,Prosaria,Business Development,GM001,0.92,No,Walter,Silva,0
As you can see the data exists in my mongo-atlas
But my mongo-shell is empty when I call db.clients.find()
server.js
const express = require('express');
const app = express();
const mongodb = require('mongodb').MongoClient;
const fs = require('fs');
const fastcsv = require('fast-csv');
const csvtojson = require('csvtojson');
require("dotenv").config()
const PORT = process.env.PORT || 3003;
//middleware
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(express.static(__dirname + 'public'));
// Global Configuration
const MONGODBURI = process.env.MONGODBURI || 'mongodb://localhost:27017/projectData';
let stream = fs.createReadStream('./gm_data.csv');
let csvData = [];
let csvStream = fastcsv
.parse()
.on('data', (data) => {
csvData.push({
date: data[0],
client: data[1],
project: data[2],
projectCode: data[3],
hours: data[4],
billable: data[5],
firstName: data[6],
lastName: data[7],
billableRate: data[8]
})
})
.on('end', () => {
csvData.shift();
console.log(csvData);
mongodb.connect(
MONGODBURI, {
useNewUrlParser: true,
useUnifiedTopology: true
},
(err, client) => {
if (err) throw err;
client
.db('gm-clients')
.collection('clients')
.insertMany(csvData, (err, res) => {
if (err) throw err;
console.log(`Inserted: ${res.insertedCount} rows`);
client.close
});
}
);
});
stream.pipe(csvStream);
//TEST ROUTE --- // http://localhost:3003/
app.get('/', (req, res) => {
res.send('Say Hello to Zee Server')
})
//routes
const customerRoutes = require('./routes/routes.js');
app.use('/customer', customerRoutes);
//Listening
app.listen(PORT, () => {
console.log('Listening on port', PORT)
})
routes.js
const express = require('express')
const router = express.Router();
const path = require('path');
let fs = require('fs');
let parse = require('csv-parse');
const csv = require('csvtojson');
const Customer = require('../models/customer.js');
//Index Route -- //http://localhost:3003/customer/allcustomers
router.get('/allcustomers', (req, res) => {
Customer.find({}, 'client', (err, data) => {
res.json({data: data});
})
})
module.exports = router;
models.js
const mongoose = require('mongoose')
const customerSchema = new mongoose.Schema({
name: String, //project col in CSV
clients: String, //client col in csv
hours: Number, // hours col in csv
billable_hours: Number, // billable col in csv
billable_amount: Number // billable rate in csv
})
// name | clients | hours | billable hours | billable amount
module.exports = mongoose.model('Customer', customerSchema);

How to use Mongoose find query in express router?

I am trying to use Mongoose find query to get the complete list of documents held in my mongodb. However for some reason, the query stopped working and hasn't worked since. I believe all my code is correct, and its not giving me any error messages either.
Routes\image.js
const router = require('express').Router();
let imageModel = require('../Models/image');
router.get('/collection',(req,res) => {
imageModel.find({},(err,data) => {
if(err) {
res.status(500).json({msg:"Cant find collection",err})
} else {
res.send(data);
}
})
})
module.exports = router;
Models \ image
let mongoose = require('mongoose');
const Schema = mongoose.Schema;
let imageSchema = new Schema({
name:String,
desc:String,
imgUrl:String
});
let model = new mongoose.model('Image',imageSchema);
module.exports = model;
index.js
const express = require('express');
const app = express();
const cors = require("cors");
const PORT = process.env.PORT || 5001;
// Routes
const imageRoute = require('./Routes/image');
app.use(express.json());
app.use(cors());
require('dotenv').config()
require('./db.config');
app.use('/image',imageRoute);
app.get('/',(req,res) => {
res.send('First Route!')
})
app.listen(PORT,() => {
console.log(`listening on port ${PORT}`)
})

Can't save to mongoDB's database

While sending a post request i written the following code :
var email = req.body.email ;
var newDetails = { email: email };
Details.create(newDetails);
console.log(newDetails);
while sending the request. The console.log shows me the correct details,
However in the mongo shell the only collection that exist is "details" and it's empty .
That's the Mongoose Schema:
var mongoose = require("mongoose");
var DetailsSchema = mongoose.Schema({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
I'm using NodeJS.
Thanks in advance.
Your Mongoose Model should be like
const mongoose = require("mongoose");
const Scheme = mongoose.Schema;
const DetailsSchema = new Scheme({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
Node js Code should be like
var detailsModel = require('../model/Details.js');//path of mongoose model
var detailsData = new detailsModel();
detailsData.email = req.body.email;
detailsData.save(function (err, savedJob) {
if (err) {
return res.send(err);
} else {
return res.send(savedJob);
}
});
To save data in mongoDB's Database
You can use this way
var detailsData = new detailsModel();
detailsData.save()
.then(business => {
res.status(200).json({'Details': 'newDetails added successfully'});
})
.catch(err => {
res.status(400).send("unable to save to database");
});
With this, you can also handle error easily.