i keep get TypeError x is not constructor - mongodb

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

Related

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)
}
})
......

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.

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

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

Mongoose model.find() function not work from second connection

In my database I have two collections admins and users.I'm using them from different express apps.Both apps connected to the same database.Now I need to fetch all users list from admin app. Here is my User model.
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../configs/config');
const uuid = require('uuid/v4');
// User Schema
const UserSchema = mongoose.Schema ({
email: {type: String,required: true,unique:true},
password: {type: String,required: true,unique:true},
created_at:{type:Date,default:Date.now()},
updated_token:{type:String,default:null,unique:true},
deleted:{type:Boolean,default:false},
activation_Token:{type:String,default:null},
isActive:{type:Boolean,default:false}
});
const User = module.exports = mongoose.model('User', UserSchema);
module.exports.getUserById = function(id, callback) {
User.findById(id, callback);
}
module.exports.getUserByEmail = function(email, callback) {
const query = {email}
User.findOne(query, callback);
}
In my admin app I use Uesr.find() function and it doesn't make any sense.Models are in different paths and I dont think that its can bring troubles.Also I'm using nginx web server for proxy-passing.