This is my Schema which is in models/adder folder:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
title: { type: String, required: true },
image: { type: String, required: true },
url: { type: String, required: true }
});
module.exports = mongoose.model('Product', schema);
Now this is my index.js where all the routes have been made for get, post and delete:
var express = require('express');
var router = express.Router();
var Product = require('../models/adder');
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.createConnection('localhost:27017/replica');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('partials/index', { title: 'Express' });
});
router.get('/adder', function(req, res, next) {
res.render('adder/adder')
})
router.post('/added', function(req, res, next) {
var products = new Product({
title: req.body.title,
image: req.body.image,
url: req.body.url
});
products.save(function(err, done) {
if (err) {
console.log(err);
} else {
console.log('that have been saved')
}
res.redirect('/');
});
});
module.exports = router;
Now whenever i am submiting the fourm products have all the data i entered I had consoled it and i am able to make conenction with my local mongoDB server. But i am not able to use save function. Can anyone guide me how to save the data which is in products .
Related
I am creating my first node js api using Mongoose and Express. Facing some issue when i try to post the data it does not work. Postman request never completes and data does not get saved. Please find attached code and help me figure out the issue. Also note that db connection gets established successfully.
//Post.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: "string",
required: true,
},
description: {
type: "string",
required: true,
},
date: {
type: "Date",
default: Date.now,
},
});
module.exports = mongoose.model("Posts", PostSchema);
// Posts.js => Routes
const express = require("express");
const Post = require("../models/post");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Posts");
});
router.post("/", (req, res) => {
try {
console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description,
});
post
.save()
.then((data) => res.json(data))
.catch((err) => res.json(err));
} catch (error) {
console.log(error);
}
});
module.exports = router;
// app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
require("dotenv/config");
const bodyParser = require("body-parser");
//Import Routes
const postRoute = require("./routes/posts");
//Middlewares
app.use(bodyParser.json());
//Routes
app.use("/posts", postRoute);
// Connect to db
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("connected to db !");
}
);
app.listen(3000);
UPDATE
Looks like something is wrong with db connection itself. Below is my connection string. I handled the mongoose connection on error and i get the error shown in screen shot.
mongodb://<dbuser>:<dbpassword>#ds023550.mlab.com:23550/roofapp
Just pasted your code here and is working fine for both post and get.
Are you able to complete the GET request?
How is your project structured?
Make sure you are importing the files correctly.
From your commented out file names you have Post.js with capital letter and you are importing posts. It seems that something is wrong in the imports.
Here is a working solution based on the code you've posted.
Files : app.js - Post.js - Router.js
app.js:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
// require("dotenv/config");
const bodyParser = require("body-parser");
//Import Routes
const postRoute = require("./Router");
//Middlewares
app.use(bodyParser.json());
//Routes
app.use("/posts", postRoute);
// Connect to db
mongoose.connect("mongodb://localhost/test",
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("connected to db !");
}
);
app.listen(3000);
Post.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: "string",
required: true,
},
description: {
type: "string",
required: true,
},
date: {
type: "Date",
default: Date.now,
},
});
module.exports = mongoose.model("Posts", PostSchema);
Router.js
const express = require("express");
const Post = require("./Post");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Posts");
});
router.post("/", (req, res) => {
try {
console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description,
});
post
.save()
.then((data) => res.json(data))
.catch((err) => res.json(err));
} catch (error) {
console.log(error);
}
});
module.exports = router;
If I set required to false, it will successfully create an object in the MongoDB database with one id. I suffer confusion sometimes, check my profile if you want. I think it's a little thing. If you need more info, just comment.
app.js
var express = require('express');
var bodyParser = require('body-parser');
var product = require('./routes/product'); // Imports routes for the products
var app = express();
var mongoose = require('mongoose'); // Set up mongoose connection
var dev_db_url = 'mongodb://localhost/Product';
var mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/products', product);
var port = 3002;
app.listen(port, () => {
console.log('Server is up on port numbner ' + port);
});
model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
name: {type: String, required: true, max: 100},
price: {type: Number, required: true},
});
module.exports = mongoose.model('Product', ProductSchema);
controller.js
var Product = require('../models/product');
//Simple version, without validation or sanitation
exports.test = function (req, res) {
res.send('Greetings from the Test controller!');
};
exports.product_create = function (req, res, next) {
var product = new Product(
{
name: req.body.name,
bags: req.body.bags
}
);
console.log(JSON.stringify(req.body))
product.save(function (err) {
if (err) {
return next(err);
}
res.send('Bags Created successfully')
})
};
router.js
var express = require('express');
var router = express.Router();
// Require the controllers WHICH WE DID NOT CREATE YET!!
var product_controller = require('../controllers/product');
// a simple test url to check that all of our files are communicating correctly.
router.get('/test', product_controller.test);
router.post('/create', product_controller.product_create);
module.exports = router;
HTTP POST: http://localhost:3002/products/create?name=Jorge&price=20
ValidationError: Product validation failed: name: Path name is
required
Can you help?
Thanks!
💡 The reason why it's error, because your req.body.name is empty or null. Why it's null or empty or undefined? Because you're not add your data in your body, when you send create request.
You can see your Endpoint:
HTTP POST: http://localhost:3002/products/create?name=Jorge&price=20
It's not about req.body, it's a req.params. So you can use req.params.name and req.params.price.
🕵️♂️ So, If you're passing your data using parameres, your code will looks like this:
exports.product_create = function (req, res, next) {
var product = new Product(
{
name: req.params.name,
price: req.params.price
}
);
console.log(req.params);
product.save(function (err) {
if (err) {
return next(err);
}
res.send('Bags Created successfully')
})
};
If you want to use req.body, than add your json object tobody if you're using Postman.
🕵️♂️ You can see the image below: An example using postman to passing your data into body, before you send create request to your backend.
So, If You're passing your data from body, than your code will looks like this:
exports.product_create = function (req, res, next) {
var product = new Product(
{
name: req.body.name,
price: req.body.price
}
);
console.log(req.body);
product.save(function (err) {
if (err) {
return next(err);
}
res.send('Bags Created successfully')
})
};
I hope it's can help you.
I'm trying to create a CRUD REST API in NodeJS, Express, and Mongodb.
I did something to break all my routes where they no longer return responses. No errors, nothing in the console, etc. I'm not sure what happened, I had it working before. Through just some console.logs I figured out it was freezing whenever it interfaced with the database.
Now, when I send a post request in Postman, it just hangs with 'Loading request'. I'm sending my request as a raw JSON in the body and a content type of application/json; charset=UTF-8 in the header.
{"username":"zezimaUsername","rsn":"Zezima","avatar":"http://secure.runescape.com/m=avatar-rs/Zezima/chat.png"}
They seem to all be hanging once they interact with Mongodb. I have Mongodb running locally with the mongod --port 27017 and created my database with two collections (user and posts) in Mongodb Compass.
I setup my db in a db.js file...
var mongoose = require('mongoose');
var url = 'mongodb://localhost:27017/my-group';
mongoose.connect(url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error: '));
module.exports = db;
And start my app with my server.js...
var express = require('express');
var api = require('./api');
var app = express();
app.use(express.json());
app.use('/api', api);
//Error handling, don't return stack trace to user, log in console.
app.use(function (err, req, res, next){
console.log(err.stack);
res.status(500).send('Something went wrong, internal server error.');
});
app.listen(3000, function(){
console.log("Listening on port 3000");
});
And define my routes in my api.js file...
var express = require('express');
var router = express.Router();
var User = require('./db/models/User');
var Post = require('./db/models/Post');
router.post('/register', function(req, res){
var user = new User(req.body);
user.save()
.then(function(item){
res.status(200).send({message: "User successfully created.", status: 200});
})
.catch(function(err){
res.status(400).send({message: "User failed to save to database", status: 400});
});
});
router.get('/user/:username', function(req, res){
var query = User.findOne({"username": req.params.username});
query.exec(function(err, user){
if(user === null){
res.status(404).send({message: "User not found", status: 404});
}else{
res.status(200).send(user);
}
});
});
router.post('/create_post', function(req, res){
var post = new Post(req.body);
post.save()
.then(function(item){
res.status(200).send({message: "Post successfully created.", status: 200});
})
.catch(function(err){
console.log(err);
res.status(400).send({message: "Post failed to save to database", status: 400});
});
});
router.get('/post/id/:id', function(req, res){
var query = Post.findOne({"_id":req.params.id});
query.exec(function(err, post){
if(post === null){
res.status(404).send({message: 'Post not found', status: 404});
}else{
res.status(200).send(post);
}
});
});
router.get('/post/boss/:boss', function(req, res){
var query = Post.find({"boss":req.params.boss});
query.exec(function(err, post){
if(post === null){
res.status(404).send({message: 'Post not found', status: 404});
}else{
res.status(200).send(post);
}
});
});
module.exports = router;
And just to be complete...my models look like...
User.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
username:{
type: String,
required: true
},
rsn:{
type: String,
required: true
},
avatar:{
type: String,
required: true
},
posts:[{
type: Schema.Types.ObjectId,
ref: 'posts'
}]
});
var user = mongoose.model('users', userSchema);
module.exports = user;
and Post.js
var mongoose = require('mongoose');
var shortid = require('shortid');
var Schema = mongoose.Schema;
var postSchema = new Schema({
_id:{
type: String,
default: shortid.generate
},
username:{
type: Schema.Types.ObjectId,
ref: 'users'
},
rsn:{
type: String,
required: true
},
avatar:{
type: String,
required: true
},
boss:{
type: String,
required: true
}
});
var post = mongoose.model('posts', postSchema);
module.exports = post;
I'm not sure what's happening, I keep reading a bunch of various tutorials and the documentation but I'm just not seeing the issue I'm having.
You have not required your db.js file in your server.js file.
Require it after var express = require('express');
let db = require("./db");
Then it will work fine.
.save function is not working without error its not inserting data into collection of a table. when i was inserting data into collection using mongodb command then data is inserting. I am also checking the mongoose connection it is working fine. when i am using else case in .save function then it will come in else condition but data is not inserting. model and routes code are bellow kindly help to resolve this issue.
var express = require('express');
var router = express.Router();
var User = require('../model/User');
var bcrypt = require('bcryptjs');
/* GET users listing. */
router.get('/register', function(req, res, next) {
res.render('register', {title: 'User registrations page !'});
});
router.get('/login', function(req, res, next){
res.render('login', {title: 'User Login page !'});
});
//Register process
router.post('/register', function (req, res) {
var name = req.body.fullname;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var newUser = new User();
newUser.name = name;
newUser.email = email;
newUser.username = username;
newUser.password = password;
newUser.save(function(err, savedUser){
if (err) {
console.log(err);
return res.status(500).send();
}
return res.status(200).send();
});
});
Creating a model user under the model folder which is including in users routes file
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true
},
username:{
type: String,
required: true
},
password:{
type: String,
required: true
}
});
var user = mongoose.model('myuser', userSchema);
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/userDet',{ useMongoClient: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(err) {
if (err) {
console.log('Connection error');
}
// we're connected!
else {
console.log('We are connected !');
}
});
module.exports = user;
#NiteshSingh when you want to get the data from html form you need to do parsing. Make sure that your html form tag action must be same with post route <form method="post" action="/register">. Try this code
var express = require('express');
var bodyParser = require('body-parser');
var mongoose=require('mongoose');
var User=require('../models/User');
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var userRouter = express.Router();
userRouter.use(bodyParser.json());
userRouter.post('/register',urlencodedParser,function(req, res, next){
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
app.use('/register',userRouter);
module.exports = userRouter;
And you can follow this link https://medium.com/#ratracegrad/hitchhikers-guide-to-back-end-development-with-examples-3f97c70e0073
Read this article from top to bottom. You will get an idea. Hope this helps...
I am following a YouTube tutorial from Jose Annunziato. I created my server.js and did all the required settings and configurations for my database connection. Now when I am posting something from the form to the server: it shows the data is sent to the server successfully but when I go to the mongo console to verify if the data is received and database is created or not. I run db it says test I run show dbs and there I can't see my new Database. I am not sure what the actual problem is because I did everything Jose said in the tutorial.
Server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blogfall2016');
var PostSchema = mongoose.Schema({
title: {type: String, required: true},
body: String,
tag: {type: String, enum:['POLITICS', 'ECONOMY', 'EDUCATION']},
posted: {type: Date, default: Date.now},
});
var PostModel = mongoose.model('PostModel', PostSchema)
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/api/blogpost", CreatePost);
function CreatePost(req, res) {
var post = req.body;
console.log(post);
PostModel.create(post);
res.json(post);
}
app.listen(3000);
If your schema and data you want to insert are matched then it should work.
Try below code. instead of PostModel.create(post);
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/nnnnnn', function (err) {
if (!err) {
console.log('connection successful');
} else {
console.log(err)
}
});
var PostSchema = mongoose.Schema({
title: { type: String, required: true },
body: String,
tag: { type: String, enum: ['POLITICS', 'ECONOMY', 'EDUCATION'] },
posted: { type: Date, default: Date.now },
});
var PostModel = mongoose.model('PostModel', PostSchema)
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/api/blogpost", CreatePost);
function CreatePost(req, res) {
var post = req.body;
console.log(post);
// static data
var post = {
title: 'asdfasdf',
body: 'asdfasdfasdfasdf',
tag: 'POLITICS',
posted: new Date()
}
var postModel = new PostModel(post);
postModel.save(function (err, data) {
if (err) {
console.log('Error', err);
} else {
console.log('data inserted');
}
});
res.json(post);
}
app.listen(3000);
Instead of below line
mongoose.connect('mongodb://localhost/blogfall2016');
Try this one to make sure that database created successfully first,
then do your operation
mongoose.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});