express: req.body is empty on PUT request (findOneAndReplace) - node.js

i have a strange behavior on my express/node/mongodb server app,
seems that only when i call a PUT request with findOneAndReplace method, this one look like empty.
In fact i have this error message for validation method:
here the code:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const methodOverride = require('method-override');
const session = require('express-session');
const passport = require('passport');
const logger = require('morgan');
const cors = require('cors');
//MODEL
const Clienti = require('./model/clienti');
app.use(bodyParser.urlencoded({limit: '10mb', extended: false}));
app.use(methodOverride('_method'));
app.use(bodyParser.json({limit: '10mb'}));
//UPDATE
app.put('/api/aggiorna_cliente/:id', function(req, res, next) {
console.log(JSON.stringify(req.body)) --> N.B. i have the correct body rendition here
console.log(JSON.stringify(req.params.id))
Clienti.findOneAndReplace(
{ _id:req.params.id },
{
address:req.body.address,
brand:req.body.brand,
cap:req.body.cap,
city:req.body.city,
civico:req.body.civico,
email:req.body.email,
fiscalcode:req.body.fiscalcode,
provincia:req.body.provincia,
utente:req.body.utente
},
function (err, post) {
if (err) return next(err);
res.json(post);
});
});
here the CLIENTI model
const mongoose = require('mongoose');
const clientiSchema = mongoose.Schema({
utente:{
type: String,
required:true
},
cap:{
type: Number,
required:true
},
civico:{
type: String,
required:true
},
city:{
type: String,
required:true
},
address:{
type: String,
required:true
},
fiscalcode:{
type:String,
required:true
},
email:{
type:String,
required:true
},
brand:{
type:String,
required:true
},
provincia:{
province: String,
sigle: String
}
});
const Clienti = mongoose.model('Clienti',clientiSchema);
module.exports = Clienti
as you can see quite all the fields are "required", that cause the validation problem on the picture above.
But if i remove the rquired field, all the data is empty (except for id)
last the way that i use service in angular
updateCustomer(customer){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.put(this.UpdateCustomer+'/'+customer._id, JSON.stringify(customer), {headers: headers})
.map((response: Response) => response.json())
}
what could it be?
Thank you for your time

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.

Mongoose not displaying data from mongoDB

i created a mongodb with a name userInfo with collection name "info" in the terminal and i created a schema in models/user_info.js.And i am not getting any values from the database at all.
my userInfo db has name,studentId,dept
My view engine is jade/pug I am trying to iterate and display the values from the database. I am not getting an error but its not displaying the values. Thanks for the help!
app.js
const express= require('express');
const path = require('path')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
mongoose.connect('mongodb://localhost/userInfo')
let db = mongoose.connection;
db.on('error',(error) => console.log(error));
db.once('open',() => console.log('Connected to Mongodb'))
const app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
let UserInfo = require('./models/user_info')
app.set('views',path.join(__dirname,'views'))
app.set('view engine','pug')
app.get('/',(req,res) => {
UserInfo.find({},function(err,info){
if(err){
console.log(err);
}else{
res.render('tabel',{
title:'user report',
info:info
});
}
})
})
user_info.js //shema
let mongoose = require('mongoose');
//Userinfo Schema
let userInfoSchema = mongoose.Schema({
name:{
type:String,
required:true
},
studentID:{
type:String,
required:true
},
dept:{
type:String,
required:true
}
});
let UserInfo = module.exports = mongoose.model('UserInfo',userInfoSchema);
In your model, you are pointing the collection name UserInfo, but your data are in 'info' collection.
So, change the collection name explicitly in your model.
Your user_info.js (schema) should be,
let mongoose = require('mongoose');
let userInfoSchema = mongoose.Schema({
name:{
type:String,
required:true
},
studentID:{
type:String,
required:true
},
dept:{
type:String,
required:true
}
});
let UserInfo = module.exports = mongoose.model('UserInfo', userInfoSchema, 'info');
In the last line, I pass the third argument, to indicate the collection name to info.

Cannot access static functions in mongoose model . the error says "unexpected token . "

I have my mongoose schema defined in user.js file.
//user.js
const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
let userSchema = new mongoose.Schema({
email: {
type:String,
require:true,
trim:true,
minlength: 1,
unique:true,
validate:{
validator: validator.isEmail
,
message: '{value} is not valid',
}
},
password:{
type:String,
required:true,
minlength:6
},
tokens: [{
access:{
type:String,
required:true
},
token:{
type:String,
required:true
}
}]
})
userSchema.statics.findByToken = function(token){
console.log('token');
let User = this;
console.log("this is: ",User);
let decoded;
try{
decoded = jwt.verify(token,'abc123')
}catch(e){
return Promise.reject();
}
return User.findOne({
_id: decoded._id,
'tokens.token': token,
'tokens.access': 'auth'
})
}
const User = mongoose.model('User', userSchema );
module.exports = {
User: User,
}
I am trying to import it into a seperate file and call the function findByToken inside app.get("users/me") route . The function is meant to receive the token as an argument and find the document associated with that token from the database.
The code is pasted below
//server.js
const express = require('express');
const {User} = require('./models/user.js');
const bodyParser = require('body-parser')
let app = express();
app.use(bodyParser.json());
process.env.port = 3000;
const PORT = process.env.port;
app.get('/users/me',(req,res)=>{
let token = req.header('x-auth')
User.findByToken(token).then((user)=>{
if(!user){
return Promise.reject();
}
res.status(200).send(req.user);
}).catch(e)=>{
res.status(401).send();
}
})
app.listen(PORT,()=>{
console.log('listening to port: ',PORT)
})
When I run the code I get this error.
module.exports = User = mongoose.model('users', UserSchema);
I don't see an export expression in your user.js

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