mongoose and node js insert/post data - node.js

I'm working with node.js, expressjs 4, and mongoose.
My mongoose shema is that:
var MachineSchema = new mongoose.Schema({
serial_num: { type: String},
description: {type: String},
nature: {type: String, sparse: true},
mark: {type: String },
type: String,
history: {
date: Date,
action: String,
description: String,
specif_infos: {
client: String,
number: Number
}
},
purchase_date: {type: Date},
actual_owner: {
first_name: {type: String},
last_name: {type: String},
phone: {type: Number},
owner_address:
{
avenue: {type: String},
city: {type: String},
country: {type: String},
postal_code: { type: Number}
}
},
actual_concess: {
name: String,
phone: Number,
concess_address:
{
avenue: String,
city: String,
country: String,
postal_code: { type: Number, min: 0, max: 99999}
}
}
});
how can i post some data?
i tried to use raw in POSTMAN but is doesn't work!
any idea please?
and for my controller: machine.js
exports.postMachines = function (req, res) {
var machine = new Machine();
machine.serial_num = req.body.serial_num;
machine.description = req.body.description;
machine.nature = req.body.nature;
machine.mark = req.body.mark;
machine.type = req.body.type;
machine.history = req.body.history;
machine.purchase_date = req.body.purchase_date;
machine.actual_owner = req.body.actual_owner;
machine.actual_concess = req.body.actual_concess;
machine.save(function (err) {
if (err) {
res.json({ message: 'la machine ne peut pas être ajoutée'});*/
res.send(err);
} else {
res.json({ message: 'machine ajoutée', data: machine});
}
});
};
exports.getMachines = function (req, res) {
Machine.find(function (err, machines) {
if (err) {
res.send(err);
}
res.json(machines);
});
};
exports.getMachine = function (req, res) {
Machine.findById(req.params.id, function (err, machine) {
if (err) {
res.send(err);
}
res.json(machine);
});
};
exports.getMachine = function (req, res) {
Machine.findOne(req.params.mark, function (err, machine) {
if (err) {
res.send(err);
}
res.json(machine);
});
};
exports.putMachine = function (req, res) {
Machine.findById(req.params.id, function (err, machine) {
if (err) {
res.send(err);
}
machine.history = [req.body.history];
machine.actual_owner = req.body.actual_owner;
machine.actual_concess = [req.body.actual_concess];
return machine.save(function (err) {
if (!err) {
console.log("machine mise à jour");
} else {
console.log("erreur : " + err);
}
return res.json(machine);
});
});
};
exports.deleteMachine = function (req, res) {
Machine.findByIdAndRemove(req.params.id, function (err) {
if (err) {
res.send(err);
}
res.json({ message: 'machine supprimée!' });
});
};
exports.deleteMachines = function (req, res) {
Machine.remove(function (err, machines) {
if (err) {
res.send(err);
}
res.json("machines supprimées");
});
};

You must do the mapping between your functions and the HTTP method, for example:
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
In your case, you shold pass the app object to your router file and do something like:
module.exports = function(app) {
postMachines = function (req, res) {
var machine = new Machine();
machine.serial_num = req.body.serial_num;
machine.description = req.body.description;
machine.nature = req.body.nature;
machine.mark = req.body.mark;
machine.type = req.body.type;
machine.history = req.body.history;
machine.purchase_date = req.body.purchase_date;
machine.actual_owner = req.body.actual_owner;
machine.actual_concess = req.body.actual_concess;
machine.save(function (err) {
if (err) {
res.json({ message: 'la machine ne peut pas être ajoutée'});*/
res.send(err);
} else {
res.json({ message: 'machine ajoutée', data: machine});
}
});
}
app.get('/machines', getMachines);
app.post('/machines', postMachines);
app.delete('/machines/:id', deleteMachines);
}

Related

array data is not being sent to mongodb

I have this schema for my project but it is not pushing the data in mongo db
let bracketModel = mongoose.Schema(
{
tournamentName: String,
gameType: String,
players: Number,
description: String,
teams: [String],
},
{
collection: "bracketsample",
}
);
here is my function
module.exports.addprocesspage = (req, res, next) => {
let newbracket = Bracket({
tournamentName: req.body.tournamentName,
gameType: req.body.gameType,
players: req.body.players,
description: req.body.description,
$addToset:{teams:[req.body.teams]},
});
Bracket.create(newbracket, (err, Bracket) => {
if (err) {
console.log(err);
res.end(err);
} else {
//refresh the bracket-list
res.redirect("/bracket-list");
console.log();
}
});
};
tried declaring cons varialble=req.body.teams but still not working.
You are missing the "new" syntax before "Bracket". Also you use the create method with the already created "Bracket", i would use save instead. Try this:
let newBracket = new Bracket({
tournamentName: req.body.tournamentName,
gameType: req.body.gameType,
players: req.body.players,
description: req.body.description,
$addToset:{teams:[req.body.teams]},
});
newBracket.save().then(() => {
res.redirect("/bracket-list");
}).catch((err) => {
console.log(err);
res.end(err);
});

how to all crud operation of project handle into some function(one module) in node.js

i want to create one module to handle all crud operation of project.
i am applying all dynamic ways into application.
please help me this way i am in some confusion.
i have created three CRUD operation for teacher and student. this all CRUD into separated file.
i want to all CRUD operation handle by one module dynamically.
i have some confusion this type of handling module.
Any idea for this type dynamic ways & Any suggestion link, tutorial, coding.
please help me.
thanks
app.js
const express = require('express');
const app = express();
const port = 2500;
const mongoose = require('mongoose');
const admin = require('./controller/admin_control');
const principle = require('./controller/principle_control');
const teacher = require('./controller/teacher_control');
const student = require('./controller/student_control');
const result = require('./controller/result_control');
mongoose.set('useCreateIndex', true);
mongoose.connect(
"mongodb://localhost:27017/school",
{ useNewUrlParser: true},
err => {
if(err) throw err.message;
console.log('mongodb connection successfully');
},
);
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use('/admin', admin);
app.use('/principle', principle);
app.use('/teacher', teacher);
app.use('/student', student);
app.use('/result', result);
app.listen(port, function(req, res){
console.log('your port is', port);
})
model/teacher.js
var mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const common = require('../controller/common');
var teacherSchema = new mongoose.Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true,
lowercase: true,
unique: true,
validate: [common._validateEmail, 'Please fill a valid email address']
},
password:{
type: String,
required: true
},
class:{
type: Number,
required: true,
unique: true
},
degree: {
type: String,
required: true
},
mobile_no:{
type: String,
required: true,
validate: [common._validMobile]
},
user_type:{
type: String,
required: true
}
});
teacherSchema.plugin(uniqueValidator);
module.exports = mongoose.model("teacher", teacherSchema);
model/student.js
var mongoose = require('mongoose');
//const uniqueValidator = require('mongoose-unique-validator');
const common = require('../controller/common');
var studentSchema = new mongoose.Schema({
// _id: mongoose.Schema.Types.ObjectId,
name:{
type: String,
required: true
},
email:{
type: String,
required: true,
lowercase: true,
unique: true,
validate: [common._validateEmail, 'Please fill a valid email address']
},
password:{
type: String,
required: true
},
class: {
type: Number,
required: true
},
roll_no: {
type: Number,
required: true
},
mobile_no:{
type: String,
required: true,
validate: [common._validMobile]
},
user_type:{
type: String,
required: true
}
});
// studentSchema.plugin(uniqueValidator);
module.exports = mongoose.model("student", studentSchema);
controller/teacher_controller.js
let express = require('express');
let router = express.Router();
let teacher = require('../model/teacher');
let admin = require('../model/admin');
let common = require('./common');
router.get('/log', function(req, res){
Promise.all([
teacher.findOne({ email: req.body.teacher})
]).then(function(data){
res.send(data);
console.log(data);
}).catch(function(err){
res.send("please valid email");
})
})
router.post('/insert_teacher', function(req, res){
teacher.create(req.body, function(err, data){
if(err){
common._requirefield(req, res)
} else {
common._insertsuccess(res, data);
}
})
});
router.get('/get_teacher', function(req, res){
teacher.find({}, function(err, data){
if(err){
common._errget(err, res);
} else {
if (data == null || data == 'undefined' || data == "") {
common._foundnull(res)
} else {
common._foundsuccess(res, data);
}
}
})
})
router.put('/edit_teacher', function(req, res){
let json = {};
teacher.update({ name: req.body.name }, req.body, function(err, data){
if(err){
common._errupdate(err, res);
} else {
if (data == null || data == 'undefined' || data == "") {
common._foundnull(res)
} else {
common._successupdate(res, data);
}
}
})
});
router.delete('/delete_teacher', function(req, res){
teacher.deleteOne({name: req.body.name}, function(err, data){
if(err){
common._errdelete(err, res);
} else {
if (data == null || data == 'undefined' || data == "") {
common._foundnull(res)
} else {
common._successdelete(res, data);
}
}
})
});
module.exports = router;
controller/student_controller.js
let express = require('express');
let router = express.Router();
let student = require('../model/student');
let admin = require('../model/admin');
let common = require('./common');
router.post('/insert_student', function(req, res){
student.create(req.body, function(err, data){
if(err){
res.send(err);
} else {
res.send(data);
}
})
})
router.get('/get_student', function(req, res){
student.find({}, function(err, data){
if(err){
common._errget(err, res);
} else {
if (data == null || data == 'undefined' || data == "") {
common._foundnull(res)
} else {
common._foundsuccess(res, data);
}
}
})
})
router.put('/edit_student', function(req, res){
student.update({ name: req.body.name }, req.body, function(err, data){
if(err){
common._errupdate(err, res);
} else {
if (data == null || data == 'undefined' || data == "") {
common._foundnull(res)
} else {
common._successupdate(res, data);
}
}
})
});
router.delete('/delete_student', function(req, res){
student.deleteOne({name: req.body.name}, function(err, data){
if(err){
common._errdelete(err, res);
} else {
if (data == null || data == 'undefined' || data == "") {
common._foundnull(res)
} else {
common._successdelete(res, data);
}
}
})
});
router.put('/change_std_rollno', function(req, res){
var filter = { class: req.body.class };
var newValues = { $set: { mobile_no: req.body.mobile_no } }
student.updateMany(filter,newValues, function(err, data){
if(err){
res.send(err);
} else {
res.send(data);
console.log(data);
}
})
})
router.delete('/std_delete_many', function(req, res){
var filter = { class: req.body.class };
student.deleteMany(filter, function(err, data){
if(err){
res.send(err);
} else {
res.send(data);
console.log(data);
}
})
})
module.exports = router;
Any idea for this type dynamic ways & Any suggestion link, tutorial, coding.
Check out this article that explains how to make a reusable CRUD.

mongoose population of documents from other collections

I'm trying to create some kind of relation in my API between Retailers and GeofencePoints. A retailer object should have a list of geofence points. I tried to follow the official docs: http://mongoosejs.com/docs/populate.html. I'm getting a http 200 response when I perform the query to PUT a geofence location for a retailer, but when I get the Retail object by the id, the geofencePoints list is still empty. What am I doing wrong? Here is my Code:
Routes
app.route('/geofencePoints')
.get(geofencePointController.GET)
.post(geofencePointController.POST)
.delete(geofencePointController.DELETE)
app.route('/geofencePoints/:point_id')
.get(geofencePointController.GETid)
.put(geofencePointController.PUTid)
.delete(geofencePointController.DELETEid);
app.route('/retailers')
.get(retailerController.GET)
.post(retailerController.POST);
app.route('/retailers/:retailer_id')
.get(retailerController.GETid)
.put(retailerController.PUTid)
.delete(retailerController.DELETEid);
app.route('/retailers/:retailer_id/geofencePoints')
.put(geofencePointController.PUTgeofencesForRetailId);
geofencePointController.js
var GeofencePoint = require('../model/geofencePoint');
var Retailer = require('../model/retailer');
exports.GET = function (req, res) {
GeofencePoint.find(function (err, points) {
if (err)
res.send(err);
res.json(points);
});
};
exports.POST = function (req, res) {
var geofencePoint = new GeofencePoint();
geofencePoint.name = req.body.name;
geofencePoint.latitude = req.body.latitude;
geofencePoint.longitude = req.body.longitude;
geofencePoint.radius = req.body.radius;
geofencePoint.save(function (err) {
if (err)
return res.json({ success: false, msg: 'Name already exists.' });
res.json({ success: true, msg: 'Successful created new geofence.' });
});
};
exports.DELETE = function (req, res) {
GeofencePoint.remove({
}, function (err, point) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted all' });
});
};
exports.GETid = function (req, res) {
GeofencePoint.findById(req.params.point_id, function (err, point) {
if (err)
res.send(err);
res.json(point);
});
};
exports.PUTid = function (req, res) {
GeofencePoint.findById(req.params.point_id, function (err, point) {
if (err)
res.send(err);
point.name = req.body.name;
point.latitude = req.body.latitude;
point.longitude = req.body.longitude;
point.radius = req.body.radius;
point.save(function (err) {
if (err)
res.send(err);
res.json({ message: 'Geofence location updated!' });
});
});
};
exports.DELETEid = function (req, res) {
GeofencePoint.remove({
_id: req.params.point_id
}, function (err, point) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
};
//===================================================================
// JOINED DATA
//===================================================================
exports.PUTgeofencesForRetailId = function (req, res) {
Retailer.find({}).populate(req.params.retailer_id).exec(function (err, geofencePoint) {
if (err) return handleError(err);
var geofencePoint = new GeofencePoint();
geofencePoint.name = req.body.name;
geofencePoint.latitude = req.body.latitude;
geofencePoint.longitude = req.body.longitude;
geofencePoint.radius = req.body.radius;
geofencePoint.save(function (err) {
if (err) return res.json({ success: false, msg: 'Something went wrong' });
res.json({ success: true, msg: 'Success' });
});
});
};
retailerController.js
var Retailer = require('../model/retailer');
exports.GET = function (req, res) {
Retailer.find(function (err, retailers) {
if (err)
res.send(err);
res.json(retailers);
});
};
exports.GETid = function (req, res) {
Retailer.findById(req.params.retailer_id, function (err, retailer) {
if (err)
res.send(err);
res.json(retailer);
});
};
exports.POST = function (req, res) {
var retailer = new Retailer();
retailer.name = req.body.name;
retailer.save(function (err) {
if (err)
return res.json({ success: false, msg: 'Name already exists.' });
res.json({ success: true, msg: 'Successful created new retailer.' });
});
};
exports.PUTid = function (req, res) {
Retailer.findById(req.params.retailer_id, function (err, retailer) {
if (err)
res.send(err);
retailer.name = req.body.name;
retailer.save(function (err) {
if (err)
res.send(err);
res.json({ message: 'Retailer updated!' });
});
});
};
exports.DELETEid = function (req, res) {
Retailer.remove({
_id: req.params.point_id
}, function (err, retailer) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
};
retailer.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var retailerSchema = new Schema({
name: {
type: String,
required: true
},
mail: {
type: String,
},
telephone: {
type: String,
},
street: {
type: String,
},
housenumber: {
type: String,
},
postalCode: {
type: String,
},
city: {
type: String,
},
slogan: {
type: String,
},
geofencePoints : [{
type: Schema.Types.ObjectId,
ref: 'GeofencePoint' }]
});
module.exports = mongoose.model('Retailer', retailerSchema);
geofencePoint.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var pointSchema = new Schema({
name: {
type: String,
required: true
},
latitude: {
type: Number,
required: true
},
longitude: {
type: Number,
required: true
},
radius: {
type: Number,
required: true
},
duration: {
type: Number,
},
});
module.exports = mongoose.model('GeofencePoint', pointSchema);
I hope someone can explain what I am doing wrong. Thx
You need to save a reference to the new created GeofencePoint in your Retailer document.
Also, I don't understand why you try to populate Retailer when you make an update (and I think you try to populate it wrong, the only element to populate here is indeed the geofencePoint, not Retailers).
exports.PUTgeofencesForRetailId = function (req, res) {
var geofencePoint = new GeofencePoint({
name: req.body.name,
latitude: req.body.latitude,
longitude: req.body.longitude,
radius: req.body.radius
});
geofencePoint.save(function (err, geofencePoint) {
if (err) return res.json({ success: false, msg: 'Something went wrong' });
Retailer.findById(req.params.retailer_id, function (err, retailer) {
if (err) return handleError(err);
retailer.geofencePoints.push(geofencePoint._id);
retailer.save(function (err, retailer) {
if (err) return handleError(err);
res.json({ success: true, msg: 'Success' });
});
});
});
};
There is certainly a better/more concise approach, accordingly to your app, but it gives an idea.

Mongo db, how to give object _id another collection's document

I have 2 collections called User and Location. In User, there is a location _id and this is an Object. Id also references the location collection. My question is what did I do wrong? When I call getUser function I want to see user information and the user's location information. What I need to do ?
User Schema
module.exports = (function userSchema() {
var Mongoose = require('mongoose');
var userSchema = Mongoose.Schema({
name: {
type: String,
require: true
},
surname: {
type: String,
require: true
},
tel: {
type: String,
require: true
},
age: {
type: String,
require: true
},
mevki_id: {
type: String,
require: true
},
location_id: [{
type: Mongoose.Schema.Types.ObjectId,
ref: 'locations'
}]
});
var collectionName = 'users';
var User = Mongoose.model(collectionName, userSchema);
return User;
})();
User Controller
function userController() {
var User = require('../models/UserSchema');
this.createUser = function (req, res, next) {
var name = req.body.name;
var surname = req.body.surname;
var tel = req.body.tel;
var age = req.body.age;
var mevki_id = req.body.mevki_id;
var lok_id = req.body.lok_id;
User.create({
name: name,
surname: surname,
tel: tel,
age: age,
mevki_id: mevki_id,
lok_id: lok_id
}, function (err, result) {
if (err) {
console.log(err);
return res.send({
'error': err
});
} else {
return res.send({
'result': result,
'status': 'successfully saved'
});
}
});
};
this.getUser = function (req, res, next) {
User.find()
.populate('lok_id')
.exec(function (err, result) {
if (err) {
console.log(err);
return res.send({
'error': err
});
} else {
return res.send({
'USERS': result
});
}
});
};
return this;
};
module.exports = new UserController();
First, your schema is wrong:
var userSchema = new Mongoose.Schema({
// ...
location_id: { type: [Mongoose.Schema.Types.ObjectId], ref: 'locations' }
})
Second, in your schema the last field name is location_id while in your controller, you change it to lok_id.
So, fix this:
User.create({
// ...
location_id: lok_id
}
and this:
User
.find()
.populate('location_id')
UPDATE
In your json the last field name is location_id, therefore, fix this too:
this.createUser = function (req, res, next) {
// ...
var lok_id = req.body.location_id;
}

mongoose update model before saving

I have a model:
const wordSchema = mongoose.Schema({
author: {type: Object, default: 'unknown'},
quote: String,
source: {type: String, default: 'unknown', index: true},
rating: {type: Number, default: 0},
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now},
});
Now after receiving a POST request to my server, I want to make a GET request to wikipedia, and get the author info, then append it to my model as an object, and write this model into my database.
app.post('/', function(req, res) {
let author = {};
let quote = new Word({
author: req.body.author,
quote: req.body.quote,
source: req.body.source,
rating: req.body.rating,
});
let authorName = req.body.author.replace(/ /g, '%20');
let url = 'https://en.wikipedia.org/w/api.php?action=query&format=json&titles=' + authorName + '&prop=pageimages|extracts&pithumbsize=200&exsentences=10&exintro=true';
request.get(url, (error, response, body) => {
if(error) {
return error;
}
let data = JSON.parse(body);
let pageID;
for(page in data.query.pages) {
pageID = page;
}
author = {
name: req.body.author,
thumbnail: data.query.pages[pageID].thumbnail.source,
flavorText: data.query.pages[pageID].extract,
};
});
// Save the quote
quote.pre('save', (next) => {
this.author = author;
})
quote.save(function(err, quote) {
if (err) {
res.send(err);
}
res.redirect('/words');
});
});
Now I tried updating the value with the .pre function, but I am getting
quote.pre is not a function
What would be the 'correct way of doing this and what am I doing wrong?
quote is not a Mongoose schema, but wordSchema is so it needs to be as follow:
wordSchema.pre('save', (next) => {
this.quote = whteverYouWantToAssignWith;
})
But actually you don't need it in your use case as far as I understand, you may achieve what you want as follow:
app.post('/', function(req, res) {
let authorName = req.body.author.replace(/ /g, '%20');
let url = 'https://en.wikipedia.org/w/api.php?action=query&format=json&titles=' + authorName + '&prop=pageimages|extracts&pithumbsize=200&exsentences=10&exintro=true';
request.get(url, (error, response, body) => {
if(error) {
return error;
}
let data = JSON.parse(body);
let pageID;
for(page in data.query.pages) {
pageID = page;
}
let quote = new Word({
author: {
name: req.body.author,
thumbnail: data.query.pages[pageID].thumbnail.source,
flavorText: data.query.pages[pageID].extract,
},
quote: req.body.quote,
source: req.body.source,
rating: req.body.rating,
});
quote.save(function(err, quote) {
if (err) {
res.send(err);
}
res.redirect('/words');
});
});
});

Resources