OverwriteModelError: Cannot overwrite `user` model once compiled - node.js

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.

Related

0 I am working on NodeJs application it's shop application. I am trying to save posts in database and I am getting this error after submitting form:

TypeError: Post is not a constructor
owoce.js
const express = require('express');
const router = express.Router();
const Post = require('../models/owoc');
router.get('/', (req,res) => {
res.send('we are on owoce');
//try {
// const owoce = await Owoc.find()
// res.json(owoce)
// }catch (err){
// res.status(500).json({ message: err.message })
// }
})
// router.get('/jablka', (req,res) => {
// res.send('we are on jablka');
//});
router.post('/', (req,res) => {
const owoc = new Post({
rodzaj: req.body.rodzaj,
kolor: req.body.kolor
})
owoc.save()
.then(data =>{
res.json(data);
})
.catch(err => {
res.json({message: err});
});
});
module.exports = router;
owoc.js it includes schema
const mongoose = require('mongoose');
const OwocSchema = new mongoose.Schema({
rodzaj: {
type: String,
required: true
},
kolor: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
//mongoose.Schema({
// username: String,
// password: String
//})
mongoose.exports = mongoose.model('Owoc', OwocSchema)
I am not sure what the problem is after looking at simmilar anwseres here
i dont see what should be changed
const Post = require('../models/owoc');
server.js adding it coz it may be usefull to troubleshoot
const express = require('express')
//const req = require('express/lib/request');
//const res = require('express/lib/response');
const app = express()
const mongoose = require('mongoose')
const bodyParser = require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
//const db = mongoose.connection('mongodb://localhost/sklep')
//MIDDLEWARES
app.use('/posts', ()=> {
console.log('This is a middleware');
});
//IMPORT ROUTES
const owoceRoute = require('./routes/owoce');
app.use('/owoce', owoceRoute);
//ROUTES
app.get('/', (req,res) => {
res.send('we are on home');
});
//connect to DB
mongoose.connect(
process.env.DB_CONNECTION ,mongoose.set('strictQuery', true), ()=> {
console.log('Connected to DB!!:))');
}); //{ useNewUrlParser: true})
//how to lisen to server
///db.on('error',(error) => console.error(error))
///db.once('open',() => console.log('connected to database'))
//db.on('connected', () => console.log('Connected to database'))
app.listen(3000, () => console.log('server started'))
I am adding screenshot and server code app despite not being sure if it will be any help
here is the screen from Postman
try this:
router.post('/create', async (req,res) => {
const owoc = await Owoc.create({
rodzaj: req.body.rodzaj,
kolor: req.body.kolor
})
.then(data =>{
res.json(data);
})
.catch(err => {
res.json({message: err});
});
});

Experiencing an issue with the .save() function in MongoDB

I am using Node.js, Express, and MongoDB for a project and in MongoDB, .save() is not working.
index.js file code:
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const mongoose = require("mongoose");
//middleware;
app.use(express.json()); //for json files;
app.use(helmet());
app.use(morgan("common"));
//routing paths;
const authUser = require("./routes/auth");
// for secrets keys;
dotenv.config();
//Connecting to Mongoose;
mongoose.connect(process.env.MONGO_PATH, {
userNewUrlParser: true, useUnifiedTopology: true
}, () => {
console.log("Connected to MongoDb");
}
)
app.use("/api/auth", authUser);
app.listen(9000, () => {
console.log("Server is Running...");
}
)
Model file name User.js:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: {
type: String,
require: true,
},
password: {
type: String,
require: true,
}
});
const User= mongoose.model("User", UserSchema);
module.exports = User;
auth.js file
const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");
//for register;
router.get("/register", async (req, res) => {
try {
const newuser = new User({
username: "herovinay",
password: "herovinay"
});
newuser.save((err)=> {
if (err) {
res.status(500).json({ msg: "internal error is here"});
}
else {
res.status(200).json({ msg: "Data saved successfully..." });
}
});
} catch (err) {
res.send("second error is here");
}
})
module.exports = router;
When accessing localhost:9000/api/auth/register, the output is msg: "internal error is here".
Screenshot of output:
Every time I tried to hit that request, the same error came over and over again.
I tried everything and was unable to save my data to the MongoDB cluster.
Change the get method to post. to create new data in the server the post method is used. and also add the await keyword before the newuser.save(),
here is a example.
const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");
//for register;
router.post("/register", async (req, res) => {
try {
const newuser = new User({
username: "herovinay",
password: "herovinay"
});
await newuser.save((err)=> {
if (err) {
res.status(500).json({ msg: "internal error is here"});
}
else {
res.status(200).json({ msg: "Data saved successfully..." });
}
});
} catch (err) {
res.send("second error is here");
}
})
module.exports = router;

Mongoose: Operation `schema.findOne()` buffering timed out after 10000ms

I have a REST API made with Node.js and I use Mongoose to connect with MongoDB. Whenever I try to interact with the DB using Mongoose, I get the timeout error.
I have made sure that the DB is running and accepts connections from my IP. Using the same connection method in other projects works for some reason.
I am using mobile hotspot connection. Could that be an issue?
server.js
const express = require('express');
const app = express();
const cors = require('cors');
const userRoutes = require('../Backend/routes/userRoutes')
const taskRoutes = require('../Backend/routes/taskRoutes')
const mongoose = require('mongoose');
require('dotenv').config()
mongoose.connect(process.env.DB_CONNECTION);
app.use(cors());
app.use(express.json());
app.use(userRoutes)
app.use(taskRoutes)
app.listen(process.env.PORT || 3000 , () => {
console.log("API is now running.")
});
userRoutes.js
const userController = require('../controllers/userController')
const express = require('express');
const router = express.Router();
router.get('/users/currentUser', userController.getCurrentUserData)
router.get('/users/:userId', userController.getUserData)
router.post('/register', userController.register);
router.post('/login', userController.login);
module.exports = router;
Method in userController that causes the error (the error is caused by no matter which method I call out)
exports.login = async (req, res) => {
if (!req.body.username || !req.body.password) {
return res.status(400).send("Missing one or all required request body fields: username, password");
}
let existingUser;
try {
existingUser = await userSchema.findOne({ username: req.body.username });
} catch(err) {
return res.status(500).send("Internal server error."); //Error comes from here
}
if (!existingUser) {
return res.status(404).send('User not found');
}
const isPasswordCorrect = await bcrypt.compare(req.body.password, existingUser.password);
if (!isPasswordCorrect) {
return res.status(401).send('Invalid credentials');
}
let token;
try {
token = jwt.sign(
{ userId: existingUser._id, username: existingUser.username, tasks: existingUser.tasks},
process.env.SECRET,
{ expiresIn: "1h" }
);
} catch (err) {
console.log(err);
return res.status(500).send("Couldn't create JWT.")
}
return res.status(200).json({ token: token });
}
User model
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const userSchema = new mongoose.Schema({
username:{
type: String,
unique: true
},
password:{
type: String
},
tasks:{
type:[mongoose.Types.ObjectId]
}
})
userSchema.pre('save', async function(next) {
const salt = await bcrypt.genSalt();
this.password = await bcrypt.hash(this.password, salt);
next();
});
module.exports = mongoose.model('user',userSchema);
.env
DB_CONNECTION="mongodb://localhost:27017/test"
SECRET='test'

Error while building my server [Route.get() requires a callback function]

I'm getting an error while building my server, which I have no idea how to fix. Any idea on how to fix this? Thank you! I'm attaching the server page but also my routes so you can see what I'm doing. The error is also listed below. Thank yo uso much!
Error:
users.post('/register' (req, res) => {
^^^^^^^^^
SyntaxError: Malformed arrow function parameter list
server.js
const express = require("express");
const cors= require("cors");
const bodyParser = require("body-parser")
const app = express();
const mongoose = require("mongoose");
const port = process.env.PORT || 5000
app.use(bodyParser.json())
app.use(cors())
app.use(
bodyParser.urlencoded({
extended: false
})
)
const mongoURI = ""
mongoose
.connect(mongoURI, {useNewUrlParser: true})
.then(() => console.log('Mongodb connected'))
.catch(err => console.log(err))
const Users = require('./routes/Users')
app.use('/users', Users)
app.listen(port, () => {
console.log('Server is running on pol.')
})
Here is more code from routes.
routes/Users.js
const express = require("express")
const users = express.Router()
const cors = require("cors")
const jwt = require("jsonwebtoken")
const bcrypt = require("bcrypt")
const User = require("../models/User")
users.use(cors())
process.env.SECRET_KEY = 'secret'
users.post('/register' (req, res) => {
const today = new Date();
const userData = {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: req.body.password,
created: today
}
User.findOne({
email: req.body.email
})
.then(user => {
if(!user) {
bcrypt.hash(req.body.password, 10, (err, hash) => {
userData.password = hash
User.create(userData)
.then(user => {
res.json({status: user.email + 'registered'})
})
.catch(err => {
res.send('error: ' + err)
})
})
} else {
res.json({error: 'User already exists'})
}
})
.catch(err => {
res.send('error:' err)
})
})
module.export = users
Its a simple typo mistake
change
users.post('/register' (req, res) => {
TO
users.post('/register', (req, res) => {

User.find() returns empty response in mongodb express

I'm working with nextjs and express .I'm implementing simple signin form.I'm sending user credential and using find() ,checking whether user exist or not.but find() returns empty response.
In terminal find() returns array of that record.
model
const mongoose = require('mongoose')
const schema = mongoose.Schema
const user = new schema({
username: { type: String} ,
password: { type: String},
role: { type: String},
})
module.exports = mongoose.model('user', user);
router.js
const express = require('express')
const router = express.Router()
const user = require('../models/user');
router.post('/user/signin', (req, res) => {
user.find({
username: req.body.username, password: req.body.password
}, (err, user) => {
console.log(user);
if (err) {
result.status(404).send({ error: 'There is some error' });
} else if (user.length == 1) {
var token = 'kkl';//token
res.send({ token });
} else {
console.log(err);
res.send('Incorrect Email and Password');
}
});
})
module.exports = router;
this.is my index.js
const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 4000
const dev = process.env.NODE_DEV !== 'production' //true false
const nextApp = next({ dev })
const handle = nextApp.getRequestHandler() //part of next config
const mongoose = require('mongoose')
const router = express.Router();
nextApp.prepare().then(() => {
const app = express();
const db = mongoose.connect('mongodb://localhost:27017/knowledgeBase')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/knowledgeBase', require('./routes/router'));
app.get('*', (req, res) => {
return handle(req, res) // for all the react stuff
})
app.listen(PORT, err => {
if (err) {
console.log(err);
throw err;
}
console.log(`ready at http://localhost:${PORT}`)
})
})
please help
What response you get when you try this?
According to the response I will edit response.
router.post("/user/signin", async (req, res) => {
if (!req.body.username) return res.status(400).send("username cannot be null");
if (!req.body.password) return res.status(400).send("Password cannot be null");
const user = await User.findOne({ username: req.body.username});
if (!user) return res.status(400).send("User not found");
if (req.body.password!== user.password)
return res.status(400).send("Invalid password.");
res.send("logined");
});

Resources