I am trying to make a simple registration route using node and express. For some reason the req.body.name is being highlighted as unresolved variable name.
While running in postman it is giving a validation error and saying "Path {PATH} is required."
My javascript code:
router.post('/', function(req, res) {
var participant = new Participant({
name:req.body.name, // this is the place where unresolved variable is coming
regno:req.body.regno,
gender : req.body.gender,
email : req.body.email,
mobile : req.body.mobile,
room : req.body.room,
adgid : req.body.adgid
});
participant.save(function(err,docs) {
if(docs) {
res.json({
"message":docs
})
}
else{
res.json({
code: '1',
message: err
})
}
});
My model file:
var mongoose = require('mongoose');
var participantSchema = mongoose.Schema({
name:{ type: String , required :true},
regno:{ type:String, required :true },
gender:{ type:String, required :true },
mobile:{ type: Number ,required :true },
email:{ type:String,required :true },
room:{ type:String ,required :true },
adgid : {type:String , required : true}
});
var Participant = mongoose.model('Participant', participantSchema);
module.exports= {Participant : Participant};
Related
I have created the following User schema
const UserSchema = mongoose.Schema(
{
fullName: {
type: String,
required: true,
index: true,
},
department: {
type: mongoose.Schema.Types.ObjectId,
ref: "Department",
required: true,
},
},
});
and my Department schema looks like the following
const DepartmentSchema = mongoose.Schema(
{
name: {
type: String,
unique: true,
required: true,
},
description: {
desc: "Description.",
type: String,
},
},
{
strict: true,
versionKey: false,
timestamps: { createdAt: "createdAt", updatedAt: "updatedAt" },
});
Now I'm able to create departments and all is working well in Postman and also my Angular application. But while creating User it only saves the department ID that I've selected or added in my form. This is the data that I've tried to create
user = {
department: "5f806be7c9a3c02c7c61f9f1"
fullName: "John Joshua"
}
and my create route controller looks like this
exports.create = async (req, res) => {
const newUser = new User({
fullName: req.body.fullName,
department: req.body.department,
});
try {
const errors = validationResult(req); // I've used express validator here
if (!errors.isEmpty()) {
res.status(400).json({ errors: errors.array() });
return;
}
const savedUser = await newUser.save();
res.json(savedUser); // Here I was expecting to return the new saved user with Department details
} catch (err) {
res.status(500).json({ message: err });
}
};
So my response is all good and working well but department only contains the ID with nothing more.
How can I send a response data with Department details? Any help is appreciated.
I have a strange one...
I've developed an api with Node/Express/Mongoose using Mongodb 3.4.9, now it's 3.4.17.
I have no ideal why, but for some reason a block of code I have been using for ages is throwing an error:
{name: "MongoError", message: "Unknown modifier: $pushAll", driver: true, index: 0, code: 9,…}
code: 9
driver: true
errmsg: "Unknown modifier: $pushAll"
index: 0
message: "Unknown modifier: $pushAll"
name: "MongoError"
Here is the code:
router.route('/addemail/:id')
// ADD EMAILS
.put(function(req, res){
Profile.findOne({'owner_id':req.params.id}, function(err, profile){
if(err)
res.send(err);
profile.emails.push({
email_type: req.body.email_type,
email_address: req.body.email_address
})
profile.save(function(err){
if(err)
res.send(err);
res.json(profile);
});
});
});
As you can see, I'm not using $pushAll in this block of code, or actually anywhere in my code.
What else could be causing this???
Thanks for any guru advise.
Update: Here is my model for the profile and I'm including the emails model next:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// SUBDOCUMENTS
var AddressesSchema = require('./profile/addresses');
var BusinessesSchema = require('./profile/businesses');
var EmailsSchema = require('./profile/emails');
var PhonesSchema = require('./profile/phones');
var SocialSchema = require('./profile/social');
// PROFILE (PARENT) MODEL
var ProfileSchema = new Schema({
//PROFILE INFO
owner_id: {
type: String,
require: true,
unique: true
},
notice: {
type: Number, // 1=profile, 2=profile and cards
},
first_name:{
type: String
},
last_name:{
type: String
},
initial:{
type: String
},
birthday:{
type: Date
},
highschool:{
type: String
},
college:{
type: String
},
facebook:{
type: String
},
linkedin:{
type: String
},
linkedin_bus:{
type: String
},
twitter: {
type: String
},
google: {
type: String
},
pinterest: {
type: String
},
user_image: {
type: String
},
contacts:[{
type:Schema.Types.ObjectId,
ref:'Contact'
}],
//SUBDOCUMENTS
emails:[EmailsSchema],
phones:[PhonesSchema],
addresses:[AddressesSchema],
businesses:[BusinessesSchema],
social:[SocialSchema]
});
module.exports = mongoose.model('Profile', ProfileSchema);
Here is what the emails model looks like:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// CONTACT (PARENT) MODEL
var EmailSchema = new Schema({
//CONTACT INFO
email: {
type: String,
require: true
},
date_registered: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Email', EmailSchema);
Mongoose probably creates a $pushAll under the hood which, however, has been removed in newer version of MongoDB as you can see here. So this is why you get the error.
I suggest you upgrade to the latest version of Mongoose which will fix this.
Also see these discussions on the Mongoose repo: https://github.com/Automattic/mongoose/issues/4455
https://github.com/Automattic/mongoose/issues/5574
Pardon me for asking but why don't you just:
// ADD EMAILS
.put(function(req, res) {
Profile.update({'owner_id': req.params.id},
{
$addToSet: {
email_type: req.body.email_type,
email_address: req.body.email_address
}
});
});
It seems you just want to add an object to an array in a mongo document based on owner_id. $addToSet does that.
You should get advantage of some mongodb nice features i.e. you could do these:
Profile.findOneAndUpdate({'owner_id':req.params.id},{addToSet:{emails:[ email_type: req.body.email_type, email_address: req.body.email_address]}}, function(err, profile){
if(err){
res.send(err);
} else {
res.json(profile);
}
}
Hi im using MongoDB + Mongoose and some strange magic happens in my app.
Ive defined my Schema as
var schema = mongoose.Schema({
username: {type: mongoose.Schema.ObjectId, ref: 'Profile' , required:true},
user: {type: mongoose.Schema.ObjectId, ref: 'Profile' , required:true},
message: String
});
As I save my Document the new entry has ben saved and stored. It has a message and a ref on Profile in username but the user field is missing.
Same happens if I rename it to userId :/ Registered a pre save listener : already missing in my callback before save
There is no Error and I do not know how to handle this situation. Please help. Would call the a team but I can not afford
Edit :
Full Schema
var mongoose = require('mongoose');
var schema = mongoose.Schema({
username: {type: mongoose.Schema.ObjectId, ref: 'Profile' , required:true},
user: {type: mongoose.Schema.ObjectId, ref: 'Profile' , required:true},
message: String
});
var autoPopulate = function(next) {
this.populate('user');
this.populate('username');
next();
};
var autoReduce = function(next) {
if(this.username){
this.username = this.username._id;
}
if(this.user){
this.user= this.user._id;
}
next();
};
schema.
pre('findOne', autoPopulate).
pre('find', autoPopulate).
pre('save', autoReduce);
module.exports = mongoose.model('News',schema);
Request Body
{
"message": "Hi",
"username": {
"_id": "5a736607bee0360014fb28e6",
"name": "Juventus Florin"
},
"user": {
"_id": "5a736607bee0360014fb28e6",
"name": "Juventus Florin"
}
}
Code
app.put("/api/news", function(request, response) {
response.header("Content-Type", "application/json");
var payload = request.body;
new News(payload).save(function(err) {
if(err){
response.status(500).send({"message": "This is an error!", "error":err, "payload":payload});
}else{
response.status(200).send(payload);
}
});
});
After saving there is an new entry , looks like (username is populated)
{
"message": "Hi",
"username": {
"_id": "5a736607bee0360014fb28e6",
"name": "Juventus Florin"
},
"_id":"5a736607bee0360014fb278h"
}
Solution :
On 1 to 1 references there is no need to
this.user = this.user._id;
Only on 1 to Many references. Removed the pre save listener autoReduce and it works
I'm trying to figure out what exactly is happening when i want to add a document to the mongoDB database.
When i try to add a document i'm getting this error:
{
"errors": {
"name": {
"message": "Path `name` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "name"
},
"kind": "required",
"path": "name"
}
},
"message": "Product validation failed",
"name": "ValidationError"
}
So i'm using Express Js and Mongoose to perform this action.
In my model: product.js
var mongoose = require('mongoose');
var productSchema = new mongoose.Schema({
name: {type: String, required: true},
category: {type: String, default: ''},
price: { type: Number, default: 0},
picture: { type: String},
quantity: {type: Number, default: 0},
status: {
type: String,
enum: ['pending', 'In Progress', 'Cancelled', 'Done'],
default: 'pending'
},
date: { type: Date, default: Date.now},
description: { type: String},
owner: {type: String}
});
var Product = mongoose.model('Product', productSchema);
module.exports = Product;
In my api routes, when i define the path for performing this action:
index.js
var express = require('express');
var router = express.Router();
var productCtrl = require('../controllers/productCtrl');
router.get('/products', productCtrl.getAllProducts);
router.get('/products/:productId', productCtrl.readProduct);
router.post('/products', productCtrl.createProduct);
router.delete('/products/:productId', productCtrl.removeProduct);
router.put('/products/:productId', productCtrl.updateProduct);
module.exports = router;
Finally, in my controller file:
productCtrl.js
var Product = require ('../models/products');
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
}
module.exports.createProduct = function (req, res){
Product
.create({
name: req.body.name,
category: req.body.category,
price: req.body.price,
picture: req.body.picture,
quantity: req.body.quantity,
status: req.body.status,
date: req.body.date,
description: req.body.description,
owner: req.body.owner
}, function createProduct(err, product){
if(err){
sendJsonResponse(res, 404, err);
return;
}
else {
sendJsonResponse(res, 201, product);
}
});
}
The behavior excepted is that i should have product document returned in json format
About my environnement, I'm using :
node.js version: 6.9.4
mongodb version: 3.4.4
express version: ~4.13.4
mongoose version: ^4.9.8
I really need help guys
The exception means that the field "name" in your model is required (you set required=true), but not provided, means you pass null or undefined to it
.create({
name: req.body.name,
req.body.name is probably undefined. Check your POST action and try console.log(req.body) to see if it is populated at all.
The exception means that the field "name" in your model is required (you set required=true), Check your req.body.name POST action.
express-validator module to perform both validation and sanitization of your data to avoid this problem. like this :
req.checkBody('name', 'Product name required').notEmpty();
var errors = req.validationErrors();
//Run the validators
var errors = req.validationErrors();
if (errors) {
//If there are errors data form invalid
res.send('');
return;
}
else {
// Data from form is valid.
}
You can try this :
productCtrl.js
var Product = require ('../models/products');
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
}
module.exports.createProduct = function (req, res){
var new_product = new Product();//instance of object (model) product
new_product.name: req.body.name,
new_product.category: req.body.category,
new_product.price: req.body.price,
new_product.picture: req.body.picture,
new_product.quantity: req.body.quantity,
new_product.status: req.body.status,
new_product.date: req.body.date,
new_product.description: req.body.description,
new_product.owner: req.body.owner
new_product.save(function(err, addprod) {//save your new product in database
if (err){
res.send(err);// error when save
}
res.send(addprod);//else return a product add
});
};
I can't save my insert
MY MODELS :
Action and Type_intervention
var mongoose = require("mongoose"),
Schema = mongoose.Schema;
var actionSchema = new Schema({
action: {
type: String,
required: true,
unique: true
},
}); //Exporter le model
module.exports = mongoose.model('Action', actionSchema);
/*-----------------------------------------*/
var mongoose = require("mongoose"),
Schema = mongoose.Schema;
var type_interventionSchema = new Schema({
type_name_intervention : {type : String},
libelle : {type : String},
Standart : {type : String},
libelle_crt : {type : String},
action : {type: Schema.ObjectId, ref: 'Action'},
});
//Exporter le model
module.exports = mongoose.model('Type_intervention',type_interventionSchema);
/*--------------------------------------*/
MY CONTROLLER:
var new_type_intervention = new Type_intervention({
type_name_intervention: req.body.type_name_intervention,
libelle: req.body.libelle,
Standart: req.body.Standart,
libelle_crt: req.body.libelle_crt,
action: req.body.action,
})
new_type_intervention.save((err, newinter) => {
if (err) {
return res.send({
message: 'Error when try to save',
'intervention': new_type_intervention,
'req.action': req.body.action,
'new_type_intervention_action': new_type_intervention.action
});
}
return res.send({
message: 'Add with succes',
'intervention': new_type_intervention
})
})
POSTMAN RUN : The error is catched (new_intervention.action not apear and there type is undefined !? )
I think this is a probleme
{ "type_name_intervention":"f",
"libelle":"f",
"Standart":"f",
"libelle_crt":"f",
"action":"test"}
//Results:
{
"message": "Error when try to save",
"intervention": {
"type_name_intervention": "f",
"libelle": "f",
"Standart": "f",
"libelle_crt": "f",
"_id": "591eb2ccd4325d0e40b2d038"
},
"req.body.action": "test",
"type of new_type_intervention_action": "undefined"
}
I found the solution :
Before save : i try to find the action_id
Action.findOne({
'action': req.body.action,
})
.exec(function (err, found_action) {
if (found_action) {
new_type_intervention.action=found_action._id; // This is GOOD practice
new_type_intervention.save();
return res.send({
'type': typeof req.body.action,
message: 'type intervention ajoutee avec succes '
})
}
})