Mongoose not interacting with DB - node.js

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");
});

Related

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;

I'm unable to add data to MongoDB database

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()

Node Express Mongo API return empty result set

I'm going to develop API using Node Express & Mongo.I have manually entered data to mongo db like below and when i try to get data from the db it shows me empty in postman.Here i have paste my project code for easy to figure out.
In the controller returned empty results.
my project structure looks like this
db.config.json
module.exports = {
//url: "mongodb://localhost:27017/TestDb"
url: "mongodb://localhost:27017/Users"
};
server.js
const express = require("express");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to Shopping List." });
});
require("./app/routes/user.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
const db = require("./app/models");
db.mongoose
.connect(db.url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Connected to the database!");
})
.catch(err => {
console.log("Cannot connect to the database!", err);
process.exit();
});
index.js
const dbConfig = require("../config/db.config.js");
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const db = {};
db.mongoose = mongoose;
db.url = dbConfig.url;
db.users = require("./user.model.js")(mongoose);
console.log(db.url);
module.exports = db;
user.contoller.js
const db = require("../models");
const User = db.users;
// Retrieve all Tutorials from the database.
exports.findAll = (req, res) => {
User.find({ isAdmin: false })
.then(data => {
console.log("datanew"+data); // <-- Empty returns here.. []
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving user."
});
});
};
user.model.js
module.exports = mongoose => {
var schema = mongoose.Schema(
{
firstName: String,
lastName: String,
password: String,
email:String,
isAdmin:Boolean
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const User = mongoose.model("user", schema);
return User;
};
user.route.js
module.exports = app => {
const users = require("../controllers/user.controller.js");
var router = require("express").Router();
// Retrieve all Tutorials
router.get("/", users.findAll);
app.use('/api/users', router);
};
It appears you manually created your MongoDB collection. Users must be in small letters so from the MongoDB interface, change Users => users and you'll be set.
Also your DB connection uri should be:
module.exports = {
url: "mongodb://localhost:27017/TestDb"
};
TestDB is the database while users is the collection. Your uri must point to a db that your code will query collections in.
Your User Model
This is just a slight change but you want to keep your code consistent. User should all be in capitalize form. MongoDB is smart to user plural and small caps automatically in the db.
module.exports = mongoose => {
var schema = mongoose.Schema(
{
firstName: String,
lastName: String,
password: String,
email:String,
isAdmin:Boolean
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const User = mongoose.model("User", schema);
return User;
};
// Actually you can remove
index.js
db.config.js files
// *********
add in server.js
const express = require('express')
const mongoose = require('monggose')
const app = express()
mongoose.connect('mongodb://localhost/TestDb');

OverwriteModelError: Cannot overwrite `user` model once compiled

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.

why do i keep getting OverwriteModelError?

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.

Resources