Can't save data to the mongodb database - node.js

I am trying to create a simple node.js API and I created a router.post method to save data and render the saved data back. But response to the post request is like {"message":""} on hitting this url http://localhost:3000/posts (POST)
body:
{
"title":"My Post",
"description":"this is the description of my first posxsxasxt"
}
Here is the app.js file
const express =require('express');
const app =express();
const mongoose=require('mongoose');
require('dotenv/config');
const bodyParser=require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
//Import Routes
const postsRoute = require('./routes/posts');
//Middleware
app.use(bodyParser.json());
app.use('/posts',postsRoute);
//Routes
app.get('/',(req,res) =>{
res.send('We are on home');
});
//Connect to DB
mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true , useUnifiedTopology: true }, ()=>
console.log("connected to DB!")
);
//how to start listening to server
app.listen(3000);
Here is the code for routes
const express =require('express');
const router=express.Router();
const Post = require('../models/Posts');
router.get('/',(req,res)=>{
res.send('We are on posts');
});
router.get('/specificposts',(req,res)=>{
res.send('We are on posts');
});
router.post('/',(req,res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
post.save()
.then( data => {
res.send(data);
})
.catch(err=>{
res.json({message:err});
});
});
module.exports = router;
Here is the schema of the database
const mongoose=require('mongoose');
//create schema
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);

Go to Atlas UI
Click on Network Access, click on ADD IP ADDRESS and select "allow access from anywhere".

Related

How can I make an entry to MongoDB with this app?

Between my app and Postman I should be able to make an entry into MongoDB, but I get this.
TypeError: Cannot read property 'title' of undefined
This is the app.js file
const express = require('express');
const app = express();
const Mongoose = require('mongoose');
require('dotenv/config')
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute)
app.use('/posts', () => {
console.log('This is a middleware.')
})
app.get('/', (req, res) => {
res.send('We are at home')
})
//Connect to DB
Mongoose.connect(process.env.DB_CONNECTION)
.then(() => {
console.log('connected to DB')
})
.catch(err => {
console.log(err);
});
app.listen(3000);
This is the posts.js file
const express = require('express');
const router = express.Router();
const Post = require('../models/Post')
var fs = require('fs');
router.get('/', (req, res) => {
res.send('We are at posts')
})
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
post.save()
.then(data => {
res.json(data);
})
.catch(err => {
res.json({message: err });
})
});
module.exports = router;
This file is the Mongoose Schema
const { json } = require('body-parser');
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
title: {
type: JSON,
required: true
},
description: {
type: JSON,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Posts', PostSchema);
Then I'm trying to post to MongoDB, through the app with Postman
Hopefully this photo should suffice.
The app is running fine locally on port 3000 and I do believe I am connecting to the database. It seems like a format problem. I don't know if the schema needs to be in JSON somehow or a configuration of Postman needs to change, but I have tried every Postman setting and tried changing the schema to JSON. I also had the type in the Mongoose file as type: String
Add this in app.js for POST Request...
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
Add that middleware on top of your routes.

node js express mongoose api save operation not working

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;

How to fix post method error using ExpressJs and MongoDB

I'm new in Express.js,MongoDb and mongoose, I have created HTTP request methods, but when running the Post method, nothing is done (nothing saved in the database), and postman still loading and it stops only when I cancel. I want to know what's wrong in my code, thank you .
router.post("/v1/department", async (req, res) => {
try {
const request = req.body
const department = new Department(request)
await department.save()
res.status(200).send(department)
} catch (error) {
res.status(500).send(error)
}
});
This is my model
const mongoose = require("mongoose");
const validator = require('validator')
const Department = mongoose.model('Department', {
name: {
type: String,
required: true,
}
,
email: {
type: String,
required: true,
trim: true,//
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Invalid email!')
}
}
}
,
createdBy: {
type: String,
default: 'SYS_ADMIN'
}
,
updatedBy: {
type: String,
default: 'SYS_ADMIN'
}
,
createdAt: {
type: Date
// ,
// default: Date.getDate()
}
,
updatedAt: {
type: Date
// ,
// default: Date.getDate()
},
isDeleted: {
type: Boolean,
default: false
}
})
module.exports = Department
This is the Index.js
const express = require("express");
const app = express()
const departmentRouter = require("../src/routes/department")
app.use(express.json())
app.use(departmentRouter)
//app.use('/', require('./routes/department'))
const port = process.env.PORT || 5000;//local machine port 3000
app.listen(port, () => (`Server running on local machine port ${port} 🔥`));
The connection to the database is :
const mongoose = require("mongoose");
//Connect to the local mongoDB database for testing the API localy
mongoose.connect('mongodb://127.0.0.1:27017/openemp-api-department', {
useNewUrlParser: true,
useCreateIndex: true
})
You're missing a few things here. Mongoose is never set up in the index.js so there is no connection to the database. This should help you follow step by step
Also in your router you're sending department1 which is never assigned.
If the link doesn't work or you need more information let me know.
For the latest version of Express which is (Express v4.16.0 and higher)
Use this in your server.js file: ----->
const express = require('express');
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
// For Express version less than 4.16.0
// ------------------------------------
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
otherwise your post request will give you error(like not recognizing any names etc)
so make sure to use these according to to express version
index.js file
const mongoose = require("mongoose");
const express = require("express");
const router = express.Router();
const axios = require("axios");
mongoose.connect(
"YourMongoUri",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
const dataSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
age: {
type: Number,
required: true,
},
});
const modelData = mongoose.model("modelData", dataSchema);
router.get("/", (req, res) => {
modelData.find((err, doc) => {
if (err) console.log(err.message);
else {
res.send(doc);
}
});
});
router.post("/", (req, res) => {
const user = new modelData({
name: req.body.name,
age: req.body.age,
});
user.save((err, doc) => {
if (err) return console.log(err);
res.send(doc);
});
});
router.put("/:id", (req, res) => {
const user = modelData.findByIdAndUpdate(
req.params.id,
{
name: req.body.name,
age: req.body.age,
},
(err, doc) => {
if (err) return console.log(err);
res.send(doc);
}
);
});
router.delete("/:id", (req, res) => {
modelData.findByIdAndDelete(req.params.id, (err, doc) => {
if (err) return console.log(err);
res.send(doc);
});
});
module.exports = router;
server.js file
const express = require("express");
const myRouter = require("./index");
const app = express();
const port = 3000;
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
s;
app.use("/myroute", myRouter);
app.listen(port, console.log("listening on port 3000"));

I can't store data into MongoDB(Atlas) on Postman (Node.js with express)

It’s my first post.
I’m trying to post a data which is object includes “title”,”body”,”snippet” into backend which I use Mongo DB Atlas.
However when I test it on postman, I can’t store those data into a schema which is prepared in model.
The error message:
“ title: MongooseError [ValidatorError]: Path `title` is required.
at new ValidatorError ”
Others(body,snippet) are also null.
app.js:
const express = require('express'),
mongoose = require('mongoose'),
cors = require('cors'),
app = express(),
blogRoutes = require('./routes/blogRoute');
// connect to mongoDB
const dbURI = '';
mongoose.connect(dbURI,{ useNewUrlParser: true,useUnifiedTopology: true } )
.then(result => {
// Listen for requests
app.listen(3000);
})
.catch((err) => console.log(err));
// Middleware & static files
app.use(express.urlencoded({ extended: true }))
// cors
app.use(cors({ origin: true, credentials: true }))
//Blog Router
app.use('/blogs/api',blogRoutes);
//404
app.use((req,res) => {
res.render('404',{ title:'Not Found' });
})
Model file:
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
const blogSchema = new Schema({
title:{
type:String,
required:true
},
snippet:{
type:String,
required:true
},
body:{
type:String,
required:true
},
}, { timestamps:true })
// create model
const Blog = mongoose.model('Blog',blogSchema);
module.exports = Blog;
Controller(store):
// Store
const blog_create_post = async (req,res) => {
const {title,snippet,body} = req.body;
try {
const blog = await Blog.create({ title,snippet,body });
res.status(201).json(blog);
console.log(blog);
} catch (error) {
res.status(400);
}
}
router:
// Store
router.post('/',blogController.blog_create_post)
Even though GET works fine, I’m stuck in this error for a long time on POST method…
I would appreciate if you suggest something.
In your mongoose schema, you have mentioned required for the title as below and while creating a new document mostly it is empty hence the error title: MongooseError [ValidatorError]: Path title is required.
at new ValidatorError
title:{
type:String,
required:true
},
Also, your Controller is catering title properly.
It can be the way you are sending data from the postman if you are sending raw and JSON then add below middleware comment
app.use(express.json());

Retreiving data from mongoose schema into my node js project

i am trying to retrieve my data from mongoose schema to my route ( say using an app named insomnia just like postman) so evertime i run the route i am getting and empty array, what is wrong with it ?
app.js
const express=require('express');
const bodyparser=require('body-parser');
const app=express();
app.use(bodyparser.urlencoded({extended:false}));
const User=require('./db/models/user').User;
require('./db/mongo');
app.get("/api/user",function(req,res){
User.find().then(function(x){
res.send(x)
console.log(req.body)
})
})
app.listen(3000);
mongo.js
const mongoose = require('mongoose');
db=mongoose.connect('mongodb://localhost/chatter_dev',
{useNewUrlParser:true});
var db = mongoose.connection;
db.once('open', function callback () {
console.log("h");
});
module.exports =mongoose;
user.js
const mongoose=require('mongoose');
const userschema=new mongoose.Schema({
username:{
type:String,
unique:true,
required:true
},
email:{
type:String
},
firstname:String,
lastname:String},{
timestamps:true}
)
exports.User=mongoose.model("User",userschema)
Before doing any work trying to get data OUT, ya gotta get a little data IN. Get into mongo and insert a few records manually. Baby steps can help you diagnose the issue.
can you try this
User.find((err, users) => {
if (err) res.status(500).send(err);
else res.json(users);
});
**App.js**
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const User = require('./models/users');
const options = {
useNewUrlParser: true,
useCreateIndex: true
};
mongoose.connect('mongodb://localhost/chatter_dev', options)
.then(connected => console.log(`Database connection establised`))
.catch(err => console.error(err));
app.get('/api/users', (req, res, next) => {
User.find().then(user => res.send(user)).catch(err => console.error(err));
})
app.listen(3000);
**Users.js (model)**
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username:{
type:String,
unique:true,
required:true
},
email:{
type:String
},
firstname:String,
lastname:String
}, {timestamps: true});
module.exports = mongoose.model('User', userSchema);

Resources