I have a basic Mongo API.
During testing, I can easily post data with postman when it is x-www-form-urlencoded but when I use raw JSON, it is just blank.
I stored the body to see what was the difference and noticed that while using the x-www-form-urlencoded format there was data but when using JSON, my object was blank and doesn't post anything.
The data schema is as follows:
var mongoose = require('mongoose');
// Setup schema
var testSchema = mongoose.Schema({
fieldone: {
type: String,
required: true
},
fieldtwo: {
type: String,
required: true
},
fieldthree: {
type: String,
required: true
},
fieldfour: String,
fieldfive: String,
fieldsix: String
});
// Export model
var test= module.exports = mongoose.model('test', testSchema);
module.exports.get = function(callback, limit) {
test.find(callback).limit(limit);
}
The controller is as below:
// Controller.js
// Import model
Test= require('./Model');
// insert new test
// Handle create actions
exports.new = function(req, res) {
const {
fieldone,
fieldtwo,
fieldthree,
fieldfour,
fieldfive,
fieldsix
} = req.body
var test= new Test(req.body);
// console log for testing if the data shows
console.log(test)
// save and check for errors
test.save(function(err) {
// if (err)
// res.json(err);
res.json({
message: 'New test created!',
data: test
});
});
};
Below is my api-routes
// api-routes.js
// Initialize express router
const router = require('express').Router();
// Set default API response
router.get('/', function(req, res) {
res.json({
status: 'alls good',
message: 'alls good',
});
});
// Import controller
const testController = require('./Controller');
// routes
router.route('/test')
.get(testController.index)
.post(testController.new);
// Export API routes
module.exports = router;
Below is my index.js:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors')
const app = express();
// Import routes
var apiRoutes = require("./api-routes");
var corsOptions = {
origin: '*',
credentials: true
};
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/api', apiRoutes);
// mongo con
mongoose.connect('mongodb://localhost/mongodojo', { useNewUrlParser: true
});
var db = mongoose.connection;
// error check
if (!db)
console.log("Error while connecting")
else
console.log("connection successful")
// Setup server port
const port = process.env.PORT || 3000;
app.get('/', (req, res) => res.send('Welcome'));
Is there anything in my code that could be causing this?
Related
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.
I am learning nodeJs. I am using mongoDB atlas database to perform the operations. I want to insert the user data but its not inserting into a collection.
Using postman i got 200 in response and "message :{} " My code is below please check and provide any solution.
index.js
const express = require('express');
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
require('dotenv/config');
const Tea = require('./models/tea')
const app = express();
app.use(express.json());
var fs = require("fs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
try {
mongoose.connect("mongodb+srv://test:<test>#firstcluster.g9kk1.mongodb.net/glocoach?retryWrites=true&w=majority",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}, (req, res) => {
console.log("Connection Successfull!!");
});
} catch (error) {
console.log("Connection error");
}
app.post('/login', async (req, res)=> {
try{
const userTea = new Tea(req.body);
await userTea.save();
res.send(userTea);
}catch(error){
console.log();
res.send({
message : error
})
}
})
app.listen(3000, ()=> {
console.log("Listening to 3000");
});
models/tea.js
const mongoose = require("mongoose"); //import mongoose
// tea schema
const TeaSchema = new mongoose.Schema({
name: {type:String, required:true},
age : Number
});
const Tea = mongoose.model('Tea', TeaSchema); //convert to model named Tea
module.exports = Tea; //export for controller use
postman
if i don't use the "userTea.save()" method
then i got response in postman in console but still data is not inserted - ?
try{
const userTea = new Tea(req.body);
// await userTea.save();
res.send(userTea);
console.log(req.body);
}
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 have a route to create a category and when I try to run it in postman it returns an error saying, "Cannot POST /api/category"
I have tried to run through my code again and again but I cannot see where is the problem.
Thank for your help in advance
My schema:
const mongoose = require("mongoose");
const CategorySchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
},
categoryName: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = Categories = mongoose.model("category", CategorySchema);
My route:
const express = require("express");
const router = express.Router();
const auth = require("../../middleware/auth");
const { check, validationResult } = require("express-validator");
const Category = require("../../models/Category");
// #route POST api/category
// #desc Create or update users category
// #access Private
router.post(
"/",
[auth, [check("categoryName", "Category name is required").not().isEmpty()]],
async (req, res) => {
console.log(categoryName);
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
}
);
module.exports = router;
this is the way my code is organized
Ok thanks to Molda I found the problem.
I was missing my route definition in my server.js file.
All good now, thank you for your help.
const express = require("express");
const connectDB = require("./config/db");
const app = express();
//Connect DB
connectDB();
// Init Middleware
app.use(express.json({ extended: false }));
app.get("/", (req, res) => res.send("API Running"));
// Define routes
app.use("/api/users", require("./routes/api/users"));
app.use("/api/auth", require("./routes/api/auth"));
app.use("/api/profile", require("./routes/api/profile"));
app.use("/api/category", require("./routes/api/category"));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
I have tried all out there but still the post request is giving me an empty. I checked in browser and also in postman the values are sent via the payload, but when getting via the router post, req.body is empty
main
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
// var bodyParser = require("body-parser"); body parser also didnt work
const app = express();
// app.use(
// bodyParser.urlencoded({
// extended: true,
// })
// );
// app.use(bodyParser.json());
app.use(cors());
app.use(express.urlencoded({ extended: true })); // interchanged this below express.json didnt work
app.use(express.json());
const PORT = 3009;
// import routes
const router = require("./routes/route");
app.use("/api", router);
// connect mongo start
const uri =
"mongodb+srv://adminuser:password#cluster0.gtkdj.mongodb.net/mydb?retryWrites=true&w=majority";
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
mongoose.connect(uri, options);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function () {
console.log("Mongo Connected");
});
app.listen(PORT, () => {
console.log("Port is connected at ", PORT);
});
model
const mongoose = require("mongoose");
const dataSchema = mongoose.Schema({
name: {
type: String,
},
});
const dataModel = mongoose.model("data", dataSchema);
module.exports = dataModel;
routes
const express = require("express");
const router = express.Router();
const dataModel = require("../model/schema");
router.post("/new_items", (req, res) => {
const data = new dataModel({
name: req.body.name,
});
console.log(data, req.body);
data
.save()
.then((item) => res.send(item))
.catch((err) => res.status(400).send(err));
});
console output { _id: 6022f0c0b3dd8f2sdc5302f9 } {}
The req body is empty. Please help me on this. Thanks
The codes were correct. But, the post request header was not present. After passing the header, it worked as intended.
await fetch("http://localhost:3009/api/new_items/", {
method: "POST",
headers: {
"Content-Type": "application/json", // this was missing
},
body: JSON.stringify(body),
})