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()
Related
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'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');
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.
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");
});
I'm trying to create a simple REST api using Postman and the MERN stack
I have the following files
server.js, Item.js, items.js, keys.js
server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const items = require('./routes/api/items');
const app = express();
// BodyParser Middleware
app.use(bodyParser.json());
// DB Config
const db = require('./config/keys').mongoURI;
//Connect to Mongo
mongoose
.connect(db)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
app.use('./api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server started'));
Item.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const ItemSchema = new Schema({
name:{
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Item = mongoose.model('item', ItemSchema);
items.js
const express = require('express');
const router = express.Router();
const Item = require('../../models/Item');
router.get('/', (req, res) => {
Item.find()
.sort({ date: -1 })
.then(items => res.json(items))
});
module.exports = router;
keys.js
module.exports = {
mongoURI: 'mongodb://tset:tset123#ds241012.mlab.com:41012/mern_shopping'
}
The server connects and connects to the DB - I get the console logs.
In postman if I try the GET and the url http://localhost:5000 I get
Cannot GET /
If I try http://localhost:5000/api/items I get
Cannot GET /api/items
Change this
app.use('./api/items', items);
to
app.use('/api/items', items);
and for http://localhost:5000 , the root you have to define with
app.get('/', function (req, res) {})