Getting Empty Array on postman when using Mongooes with Node JS - node.js

I'm trying to post data in my MongoAtlas using Mongoose on Express and NodeJS. But Postman is returning a empty array. What I'm doing wrong
Database: mongodb+srv://username:password#clusterName.8xpcg.mongodb.net/databaseName?retryWrites=true&w=majority
Here are the FilesServer.js
const express = require('express');
const server = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
server.use(bodyParser.json());
//Importing Routes
const mcqRoutes = require('./routes/mcq');
const { application } = require('express');
//Routes
server.use('/mcq', mcqRoutes);
//DB Connection
mongoose.connect('mongodb+srv://<username>:<password>#<clusterName>.8xpcg.mongodb.net/<databaseName?retryWrites=true&w=majority', ()=>
console.log('DB Connected')
)
//Server Listening Port
server.listen(6969);
MCQ Route File
const express = require('express');
const router = express.Router();
const mcq = require('../models/mcq');
router.get('/', (req, res)=> {
res.send('We are on MCQS Homepage');
})
router.post('/', async (req, res)=> {
const Mcq = new mcq ({
"_id": req.body._id,
"m_title": req.body.m_title,
"m_slug": req.body.m_slug,
"m_question": req.body.m_question,
"m_alternatives": req.body.m_alternatives,
"m_number": req.body.m_number,
"m_subject": req.body.m_subject,
"m_language": req.body.m_language
});
try {
const saveMcq = await mcq.save();
res.json(saveMcq);
} catch(err){
res.json({ message: err});
}
})
module.exports = router;
MCQ Model
const mongoose = require('mongoose');
const McqScheme = mongoose.Schema({
_id: {type: Number, require: true},
m_date: {type: Date, default: Date.now},
m_title: {type: String, require: true},
m_slug: {type: String, require: true},
m_question: {type: String, require: true},
m_alternatives: {type: Array, require: true},
m_number: {type: String},
m_class: {type: String},
m_subject: {type: String},
m_type: {type: String},
m_board: {type: String},
m_paper: {type: String},
m_unit: {type: String},
m_language: {type: String},
});
module.exports = mongoose.model('mcq', McqScheme);
PostMan Response

In MCQ Router File Try Block has mcq.save(); in wrong Case.
After that I got buffering timed out after 10000ms Error. In Server.js File I add code in mongoose.connect. mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true, useUnifiedTopology: true}) .then(() => console.log("Database connected!")) .catch(err => console.log(err)); and also update my IP Address in MongoAtlas

Related

My Post function not working with Postman heres in MonogDb

To start with I am noob in node.js and MongoDb and working with tutorial with Lama Dev social media as a basic project kindly help
in Postman
error 404 is coming
where in the video it's 200 ok
I have copied main code for 100-1000 times help
This Is my auth.js file
//auth.js
const router = require("express").Router();
const User = require("../models/User");
//register
router.post("/register", async (req, res) =>{
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
try{
const user = await newUser.save();
res.status(200).json(user);
} catch(err) {
console.log(err);
}
});
module.exports = router;
This Is my User.js file in models folder
//User.js
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
username: {
type: String,
require: true,
min: 3,
max: 20,
unique: true,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
},
profilePicture: {
type: String,
default: "",
},
coverPicture: {
type: String,
default: "",
},
followers: {
type: Array,
default: [],
},
followings: {
type: Array,
default: [],
},
isAdmin: {
type: Boolean,
default: false,
},
}, {timestamps: true});
module.exports = mongoose.model("User", UserSchema);
This Is my index.js file
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const userRoute = require("./routes/users");
const authRoute = require("./routes/auth");
dotenv.config();
mongoose.connect(process.env.MONGO_URL, ()=> {
console.log("MongoDb Connected");
});
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("dev"));
app.use("/api/users", userRoute);
app.use("/api/auth", authRoute);
app.listen(8800, ()=>{
console.log("Backhend server is running");
})
And this is a screenshot of postman
Postman ScreenShot Click here
Your POSTMAN screenshot shows your HTTP verb being GET, but the route your registered is using POST. Try changing the verb in POSTMAN.

SyntaxError: Unexpected token b in JSON at position 3

i am new to MERN framework
try to use postman to test my get and post request. but keep getting this error SyntaxError: Unexpected token b in JSON at position 3
here is my schema -------------------------
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
sex: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
password: {
type: String,
required: true
},
admin: {
type: Boolean,
default: true
}
});
module.exports = User = mongoose.model("user", UserSchema);
here is my route---------------------
const express = require("express");
const router = express.Router();
const User = require("../../models/user");
router.get("/", (req, res) => {
User.find()
.sort({ age: -1 })
.then(users => res.json(users));
});
router.post("/", (req, res) => {
const newUser = new User({
firstname: req.body.firstname
});
newUser.save().then(user => res.json(user));
});
module.exports = router;
here is my server------------------
const express = require("express");
const mongoose = require("mongoose");
const users = require("./routes/api/users");
const app = express();
app.use(express.json());
const db = require("./config/keys").mongoURI;
mongoose
.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
app.use("/api/users", users);
const port = 5000;
app.listen(port, () => console.log(`server started on port ${port}`));
please help!! stuck for whole day
You do not need express.json() for GET routes. So please try moving app.use(express.json()); to route file before POST request.
Also if you are using express version >= 4, please use app.use(bodyParser.json()) from body-parser package.

SyntaxError: Unexpected token } in JSON at position 102

I created a simple node/express api connected to mongo atlas, i try to send post requests to add new data to the database with rest client extension in vscode but keep on running into the above error not sure where I have messed up in my code
main server file with middleware
const express = require("express");
const app = express();
const coolapi = require("./api/coolapi");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
dotenv.config();
mongoose.connect(process.env.DB_ACCESS, { useUnifiedTopology: true }, () => {
console.log("DB connected");
});
app.use(express.json());
app.use("/api/coolapi", coolapi);
app.listen(3000, () => {
console.log("server is running");
});
File with express Router
const express = require("express");
const router = express.Router();
const coolioObj = require("../models/CoolModel");
router.post("/signup", (request, response) => {
const coolPerson = new coolioObj({
username: request.body.username,
email: request.body.email,
password: request.body.password,
});
coolPerson
.save()
.then((data) => {
response.json(data);
})
.catch((error) => {
response.json(error);
});
});
module.exports = router;
file with mongoose schema
const mongoose = require("mongoose");
const coolioSchema = mongoose.Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("coolioDB", coolioSchema);
request being sent
POST http://localhost:3000/api/coolapi/signup http/1.1
Content-Type: application/json
{
"username":"samthingsoweto",
"email":"sams#amapiano.co",
"password":"KabzaDaSmall",
}
JSON arrays doesn't support a comma after the last item. That is the cause of the error. Delete the last comma in all JSON arrays.
date: {
type: Date,
default: Date.now,
}, <---
{
"username":"peoplefrom",
"email":"peopleperson#email.com",
"password":"peoplepassword123", <---
}

TypeError: Cannot read property 'comment_text' of undefined

I've declared a file called commentSchema which has some fields:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const moment = require('moment');
var commentSchema = new Schema ({
comment_text: {type: String, required: true},
user_token: {type: String, required: true},
activity_id: { type: Schema.ObjectId, ref: 'Activity', required: true },
is_hidden: { type: Boolean, "default": false },
created_at: { type: Number, "default": moment().unix() },
updated_at: { type: Number, "default": moment().unix() }
})
module.exports = mongoose.model('Comment', commentSchema);
and this is my router file:
var Router = require('router');
var router = Router();
var express = require('express');
var app = express();
// importing Models
var userSchema = require('./models/userSchema.js');
var activitySchema = require('./models/activitySchema.js');
var commentSchema = require('./models/commentSchema');
// Parsing the informations get from the client
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
router.get('/comments', (req, res) => {
});
router.post('/comment', (req, res) => {
var newComment = {
comment_text: req.body.comment_text,
user_token: req.body.user_token,
activity_id: req.body.activity_id
}
console.log(newComment);
commentSchema.create(newComment, (err) => {
if (err){
console.log(err);
}
else{
console.log('DONE!');
}
})
})
module.exports = router;
I'm trying to send post request using POSTMAN but I get the following error:
Cannot read property 'comment_text' of undefined
From the documentation of router. It says you have to use following:
router.use(bodyParser.json())

Post Error - Node.JS (Payload)

Today when require a post in my server (Local) with a base64 image are returning this error:
Frontend are using AngularJS
Backend using MongoDB,Node.JS,Mongoose and NodeRestFULL
Front
Error backend
Here my server.js
const express = require('express')
const server = express();
//transform params to int
const queryParser = require('express-query-int')
//const allowCors = require('./cors')
server.use(function(req,res,next){
res.header('Access-Control-Allow-Origin','*')
res.header('Access-Control-Allow-Methods','GET,POST,OPTIONS,PUT,PATCH,DELETE')
res.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept')
res.header('Access-Control-Allow-Credentials', true);
next()
})
server.use(queryParser())
server.use(bodyParse.text({type:'*/*'}))
server.use(bodyParse.urlencoded({limit: '50mb', extended: true}))
server.use(bodyParse.json({type:'json/*', limit: '50mb'}))
//server.use(bodyParse.urlencoded({limit: '50mb'}));
server.listen(port, function(){
console.log(`BACKEND está rodando na porta ${port}`)
})
module.exports = server
loader.js
const server = require('./config/server')
require('./config/database')
require('./config/routes')(server)
Here my schema for mongodb
const restful = require('node-restful')
const mongoose = restful.mongoose
//Schema para os comprovantes
const reciboProventoSchema = new mongoose.Schema({
name: { type: String, required: true},
month: { type: String, required: true},
description: { type: String, required: true},
imgBase: {type: String, required: true}
})
module.exports = restful.model('BillsPaysProv', reciboProventoSchema)
Here i'll make basic services
//Import schemas
const BillsPaysProv = require('./billsProv')
//Create service to post a mensage contact
BillsPaysProv.methods(['get','put','post','delete'])
BillsPaysProv.updateOptions({new: true, runValidators: true})
module.exports = BillsPaysProv

Resources