I get the following error when I start the server:
throw new _mongoose.Error.OverwriteModelError(name);
^ OverwriteModelError: Cannot overwrite User model once compiled.
at new OverwriteModelError (/home/pranav/exercise-tracker/mern-exercise-tracker/backend/node_modules/mongoose/lib/error/overwriteModel.js:20:11)
my user.model.js file
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
}
},
{
timestamps: true
}
);
const User = mongoose.model("User", userSchema);
module.exports = User;
My users.js
const router = require("express").Router();
let User = require("../models/user.model");
router.route("/").get((req, res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json("Error: " + err));
});
router.route("/add").post((req, res) => {
const username = req.body.username;
const newUser = new User({ username });
newUser
.save()
.then(() => res.json("User added!"))
.catch(err => res.status(400).json("Error: " + err));
});
module.exports = router;
server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors);
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB connection established");
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
app.listen(port, () => {
console.log('Server is running on port : ' + port);
})
Replace
const User = mongoose.model("User", userSchema);
with
const User = mongoose.models['User'] || mongoose.model("User", userSchema);
When your code is running user.model.js is probably being called again, thus calling the initial definition.
Note the models being used in the OR. That method returns an object containing all defined models. It can also be written as mongoose.models.User.
Related
I'm trying to add data in the form of users to my MongoDB database which is in my local drive, but no data is being added according to post requests on postman. I have written an API to handle this post request on userRoute file. Below is the file.
const User = require("../models/userModel");
const express =require("express");
const router = express.Router();
//Fetching all users from the database
router.route("/").get((req,res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json(`There was an error: ${err.message}`));
});
//Adding user to the database
router.route("/add").post((req,res) =>{
const username = req.body.username;
const newUser = new User({username});
newUser.save()
.then(() => res.json("User added successfully!!"))
.catch(err => res.status(400).json(`There was an error:${err.message}`))
});
module.exports = router;
Below is also my User schema in the userModel file
const mongoose = require ("mongoose");
const Schema = mongoose.Schema
const userSchema = new Schema(
{
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 5,
maxlength: 15
}
},
{
timestamps: true
}
)
const User = mongoose.model("User",userSchema);
module.exports = User;
My server file containing the connection to the database and routing
//require the installed packages
const express = require("express");
const cors = require("cors");
const mongoose = require ("mongoose");
const res = require("express/lib/response");
const App = express();
require("dotenv").config();
//middlewares
App.use(cors());
App.use(express.json());
//setting environment variables and explicitly declared variables
const port = process.env.PORT || 3000;
const db = process.env.MONGODB_URI || "mongodb://localhost/tizi";
//routes
const exerciseRoute = require("./routes/exerciseRoute");
const userRoute = require("./routes/userRoute");
//App to use required routes(Use App.set and not App.use)
App.set("/Users",userRoute);
App.set("/Exercises",exerciseRoute);
//setting up server
App.listen(port,() =>{
console.log(`Server is running on port : ${port}`)
});
//connecting to database
mongoose.connect(db,
{
useNewUrlParser:true,
useUnifiedTopology : true
},
(err) => {
err
? console.log(`there is a problem: ${err.message}`)
: console.log("connected to database successfully");
});
//maintaining connection to database
mongoose.connection;
Try to use
await User.create({username});
Instead of save()
I am working with mongodb right now for creating an android app using react native.My problem is i am not able to post data to collection in mongodb.
My app.js code
const express = require("express");
const app = express();
const morgan = require("morgan");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
app.use(cors());
app.options("*", cors());
//middleware
app.use(express.json());
app.use(morgan("tiny"));
//Routes
const categoriesRoutes = require("./routes/categories");
const productsRoutes = require("./routes/products");
const usersRoutes = require("./routes/users");
const ordersRoutes = require("./routes/orders");
const api = process.env.API_URL;
app.use(`${api}/categories`, categoriesRoutes);
app.use(`${api}/products`, productsRoutes);
app.use(`${api}/users`, usersRoutes);
app.use(`${api}/orders`, ordersRoutes);
//Database
mongoose
.connect(process.env.CONNECTION_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: "eshop-database",
})
.then(() => {
console.log("Database Connection is ready...");
})
.catch((err) => {
console.log(err);
});
//Server
app.listen(3000, () => {
console.log("server is running http://localhost:3000");
});
My categories.js:
const {Category} = require('../models/category');
const express = require('express');
const router = express.Router();
router.get('/', async (req, res) =>{
const categoryList = await Category.find();
if(!categoryList) {
res.status(500).json({success: false})
}
res.send(categoryList);
})
router.post('/', async (req,res)=>{
let category = new Category({
name: req.body.name,
icon: req.body.icon,
color: req.body.color
})
category = await category.save();
if(!category)
return res.status(404).send('The category cannot be created!')
res.send(category);
})
module.exports = router;
My category.js:
const mongoose = require('mongoose');
const categorySchema = mongoose.Schema({
name: {
type: String,
required: true,
},
icon: {
type: String,
},
color: {
type: String,
}
})
exports.Category = mongoose.model('Category', categorySchema);
Through postman tool i checked it but there is no error even though i am unable to post the data and in mongodb database it is displaying as Query Results: 0
I keep getting a type Error when posting to my exercises. here is my exercises route:
const router = require("express").Router();
let Exercise = require("../models/exercise.model.js");
//get all exercises
router.get("/", (req, res) => {
Exercise.find()
.then(exercises => res.json(exercises))
.catch(err => res.status(400).json("error: " + err));
});
//add an exercise
router.route("/add").post((res, req) => {
//parse req.body
const username = req.body.username;
const description = req.body.description;
const duration = Number(req.body.duration);
const date = Date.parse(req.body.date);
//create new exercise object
const newExercise = new Exercise({
username,
description,
duration,
date
});
//save newExercise object
newExercise
.save()
.then(() => res.json("Exercise Added!"))
.catch(err => res.status(400).json("error: " + err));
});
module.exports = router;
and here is my model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// create exercise data model
const exerciseSchema = new Schema(
{
username: {
type: String,
required: true
},
description: {
type: String,
required: true
},
duration: {
type: Number,
required: true
},
date: {
type: Date,
required: true
}
},
{
timestamps: true
}
);
const Exercise = mongoose.model("Exercise", exerciseSchema);
module.exports = Exercise;
I've tried to change the route to router.post instead of router.route, I've tried changing the data model.
as well as my server.js:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const cors = require("cors");
//middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
require("dotenv").config();
//environment
const port = process.env.PORT || 5000;
//mongoose establish connection
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB connection established successfully");
});
//routers for users and exercises
const exercisesRouter = require("./routes/exercises");
const usersRouter = require("./routes/users");
app.use("/exercises", exercisesRouter);
app.use("/users", usersRouter);
//error log
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(`error: ${err}`).next();
});
app.listen(port, () => {
console.log(`server is up and running on port: ${port}`);
});
Here is the error logged in Insomnia:
Any Help is greatly appreciated!
You are misplace req and res in router.route("/add").post((res, req) => {.
Fix it: router.route("/add").post((req, res) => {
I am facing this issue. I looked online for hours to find out what the problem is before posting here. I keep getting this error OverwriteModelError: Cannot overwrite ``user`` model once compiled. after sending a post request via postman and I can't find out what's going on. could you help me find out what's going on? thank you so much in advance!
server.js
const express = require("express");
const app = express();
const user = require("./routes/user");
const connectDB = require("./config/db");
connectDB();
app.use(express.json({extended: false}));
app.get("/", (req, res) => {
res.send("welcome to our api");
});
app.use("/user", user);
const PORT = 3000 || process.env.PORT;
app.listen(PORT, () => {
console.log(`PORT ${PORT} listening and refeshing...`);
});
db.js
const mongoose = require("mongoose");
const connectDB = () =>
mongoose
.connect(
"some database",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
)
.then(
() => {
console.log("mongoDB conneted");
},
(err) => {
console.log(err);
}
);
module.exports = connectDB;
user.js
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const {body, validationResult} = require("express-validator");
router.get("/", (req, res) => {
res.send("hello");
});
router.post(
"/",
[
// password must be at least 5 chars long
body("email").isEmail(),
body("password").not().isEmpty(),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty) {
return res.status(400).json({errors: errors.array()});
}
try {
const UsersSchema = mongoose.Schema({
email: {type: String, required: true},
password: {type: String, required: true},
});
var users = mongoose.model("user", UsersSchema);
var user = new users({
email: req.body.email,
password: req.body.password,
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(req.body.password, salt);
user.save((err, user1) => {
if (err) {
console.log("error posing user");
throw err;
}
});
console.log(user.id);
const payload = {
user: {
id: user.id,
},
};
} catch (error) {
console.log(error);
res.status(400);
}
}
);
module.exports = router;
Every time the route runs it tries to create a schema which is already created.Mongoose create the collection with the first argument user by converting it to plural i.e. users.
Code never executes to the console.log("in") so findOne is not being run. RoboT3 also doesnt show auth db. Mongo version is the latest 4.0.3.
controllers/authentication.js
const User = require('../models/user');
exports.signup = (req, res, next) => {
console.log(req.body)
const email = req.body.email;
const password = req.body.password;
// check for duplicate users by email
User.findOne({email: email}, (err, existingUser) => {
console.log("in")
if (err) {return next(err)}
// if duplicate found, return error
if (existingUser) {
return res.status(422).send({error: 'Email is in use'});
}
const user = new User({
email: email,
password: password
});
user.save((err) => {
if (err) {return next(err); }
res.json(user);
})
});
// if not, create and save record and return
}
index.js
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const morgan = require ('morgan');
const router = require('./router');
const mongo = require('mongodb');
mongo.connect('mongodb://localhost:27017/auth', { useNewUrlParser: true });
const App = express();
// App setup
App.use(morgan('combined'));
App.use(bodyParser.json());
router(App);
// Server setup
const port = process.env.PORT || 3090;
const server = http.createServer(App);
server.listen(port);
console.log("server running on port " + port);
router.js
const authentication = require('./controllers/authentication');
module.exports = function (app) {
app.post('/signup', authentication.signup);
}
models/user.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema ({
email: {type: String, unique: true, lowercase: true},
password: String
});
const ModelClass = mongoose.model('user', userSchema);
module.exports = ModelClass;
Why not use mongoose in your index.js ?
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/auth', { useNewUrlParser: true });
let db = mongoose.connection;
db.once('open', function callback () {
console.log("connected to db");
});