mongoose population of documents from other collections - node.js

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.

Related

In Mongo, If a document I'm saving "Prateek" then I don't want on the next create operation even the "prateek" or "praTEEK", etc is saved

//** If I'm adding a new document with the name: "India", then I don't want that the DB allow another name with the name: "INDIA", "india", "indIA", etc. I'm new and learning, help would be great!!**
// Controller
var Dinosaur = require('../models/dinosaurs');
//addDino
module.exports.addDino = (req, res) => {
var name = req.body.name;
var type = req.body.type;
var height = req.body.height;
var weight = req.body.weight;
var Period = req.body.Period;
req.checkBody('name', 'Name is required').notEmpty();
var errors = req.validationErrors();
if (errors)
return res.status(400).send({
message: 'Name is Required'
});
else {
let newDino = {
name: name,
type: type,
height: height,
weight: weight,
Period: Period
}
Dinosaur.addDino(newDino, (err, result) => {
if (err) {
if (err.name) return res.status(409).send({
message: name + ' Already Exist'
});
else if (err.url) return res.json({ status: false, error: { url: "Url already exist" }, message: err.url });
else return res.json(err, "Server Error");
}
else {
return res.status(200).send({
message: "Done"
});
}
});
}
}
// Model
var mongoose = require('mongoose');
//dinosaur schema
var DinosaurSchema = mongoose.Schema({
name: {
type: String,
unique: true
},
type: {
type: String
},
height: {
type: Number
},
weight: {
type: Number
},
Period: {
type: String
}
});
var Dinosaur = mongoose.model('dinosaur', DinosaurSchema);
//add
module.exports.addDino = (query, callback) => {
Dinosaur.create(query, callback);
}
// GetAll, Already Created a new document with the name "Brachiosaurus"
// > Create, a new create with the first letter lower case "brachiosaurus", Don't want it to be pushed.
//Get All, Got pushed.
just add lowercase prop to Schema.
Schema
const DinosaurSchema = mongoose.Schema({
name: {
type: String,
unique: true,
required: true,
lowercase: true,
},
// ...
)}
first it will convert name into lowercase then it will look for duplicates. and it will throw error if it founds.
With the help of Apoorva & brainstorming for a bit, I come up with this solution.
// Controller
const { json } = require('express/lib/response');
var Dinosaur = require('../models/dinosaurs');
//addDino
module.exports.addDino = (req, res) => {
var name = req.body.name;
var type = req.body.type;
var height = req.body.height;
var weight = req.body.weight;
var Period = req.body.Period;
req.checkBody('name', 'Name is required').notEmpty();
var errors = req.validationErrors();
if (errors)
return res.status(400).send({
message: 'Name is Required'
});
else {
let newDino = {
name: name.toLowerCase(),
type: type,
height: height,
weight: weight,
Period: Period
}
Dinosaur.addDino(newDino, (err, result) => {
if (err) {
if (err.name) return res.status(409).send({
message: name + ' Already Exist'
});
else if (err.url) return res.json({ status: false, error: { url: "Url already exist" }, message: err.url });
else return res.json(err, "Server Error");
}
else {
return res.status(200).send({
message: "Done"
});
}
});
}
}
//Update
module.exports.updateDino = (req, res) => {
let _id = req.body.id;
let name = req.body.name;
let type = req.body.type;
let height = req.body.height;
let weight = req.body.weight;
let Period = req.body.Period;
req.checkBody('name', 'Name is required').notEmpty();
var errors = req.validationErrors();
if (errors)
return res.status(400).send({
message: 'Name is Required'
});
else {
var updateDino = {
name: name.toLowerCase(),
type: type,
height: height,
weight: weight,
Period: Period
}
Dinosaur.updateDino({ _id: _id }, updateDino, (err, result) => {
if (err) return res.json({ status: false, message: err });
else
return res.status(200).send({
message: "Updated"
});
});
}
}
//delete
module.exports.deleteDino = (req, res) => {
let name = req.body.name;
req.checkBody('name', 'Name is required').notEmpty();
var errors = req.validationErrors();
if (errors)
return res.status(400).send({
message: 'Name is Required'
});
else {
Dinosaur.deleteDino(name.toLowerCase(), (err, result) => {
if (err) {
return err;
}
else if (result.deletedCount == 0) {
res.status(400).send({
message: 'Not Found'
});
}
else
return res.status(200).send({
message: 'Deleted'
});
});
}
}
//GetByName
module.exports.getDino = (req, res) => {
let query = req.body.name;
req.checkBody('name', 'Name is required').notEmpty();
var errors = req.validationErrors();
if (errors)
return res.status(400).send({
message: 'Name is Required'
});
else {
Dinosaur.getDino({ name: query.name.toLowerCase() }, (err, result) => {
if (err)
return res.status(400).json("Not Found");
else if (result == null)
return res.status(400).json('Not Found');
else {
return res.json(uppercase(result.name));
}
});
}
}
module.exports.getAllDino = (req, res) => {
var query = {};
Dinosaur.listDino(query, (err, result) => {
if (err)
res.json(err);
else
return res.status(200).json(result);
});
}
function uppercase(str) {
var arr = str.toString().split(' ');
var newarr = [];
for (var i = 0; i < arr.length; i++) {
newarr.push(arr[i].charAt(0).toUpperCase() + arr[i].slice(1));
}
return newarr.join(' ');
}
// Model*
var mongoose = require('mongoose');
//dinosaur schema
var DinosaurSchema = mongoose.Schema({
name: {
type: String,
unique: true
},
type: {
type: String
},
height: {
type: Number
},
weight: {
type: Number
},
Period: {
type: String
}
});
DinosaurSchema.index({ user_id: 1, name: 1, res_type: 1, level: 1 }, { unique: true });
var Dinosaur = mongoose.model('dinosaur', DinosaurSchema);
//add
module.exports.addDino = (query, callback) => {
Dinosaur.create(query, callback);
}
//updateDino
module.exports.updateDino = (query, data, callback) => {
Dinosaur.findByIdAndUpdate(query, data, callback);
}
//remove
module.exports.deleteDino = (query, callback) => {
Dinosaur.deleteOne({ name: query }, callback)
}
//getDino
module.exports.getDino = (query, callback) => {
Dinosaur.findOne(query, callback);
}
//getAllDino
module.exports.listDino = (query, callback) => {
Dinosaur.find(query, callback).sort({ "name": 1 });
}

Mongoose population: How to create a Schema for a model and populate it?

I'm trying to create a model favorites.js and populate it with user.js and dishes.js, so if a user posted a favourite dish using only the id of that dish, it will store also the user and the list of favourites of that user.
Here is what I have done so far. As I'm new to this my code could have more problems than what I think. Here is my favourites model and favRouter; see how they are populated.
models/ favorites:
var mongoose = require('mongoose');
//var Dishes = require('../models/dishes');
var Schema = mongoose.Schema;
var timestamps = require('mongoose-timestamp');
mongoose.Promise = global.Promise;
// create schema
var favSchema = new Schema({
id: {
type: String,
required: true
},
createdBy: {
type: Schema.ObjectId,
ref: 'User'
},
dishes: {
type: Schema.ObjectId,
ref: 'Dish'
}
},{
timestamps: true
});
var Favorites = mongoose.model('favorites', favSchema);
module.exports= Favorites;
models/dishes:
// Dependencies
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//var timestamps = require('mongoose-timestamp');
require('mongoose-currency').loadType(mongoose);
var Currency = mongoose.Types.Currency;
mongoose.Promise = global.Promise;
// create schema
var commentSchema = new Schema({
rating: {
type: Number,
min: 1,
max: 5,
required: true
},
comment: {
type: String,
required: true
},
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
},{
timestamps: true
});
var dishSchema = new Schema({
name: {
type: String,
required: true,
unique: true
},
image:{
type: String,
required: true,
},
category: {
type: String,
required: true,
},
label: String || '',
price: Currency,
description: {
type: String,
required: true
},
comments: [commentSchema]
},{
timestamps: true
});
dishSchema.path('price').get(function(num) {
return (num/100);
});
dishSchema.path('price').set(function(num) {
return (num )
});
// model
var Dishes = mongoose.model('Dish', dishSchema);
module.exports= Dishes;
modles/user:
// Dependencies
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//var timestamps = require('mongoose-timestamp');
require('mongoose-currency').loadType(mongoose);
var Currency = mongoose.Types.Currency;
mongoose.Promise = global.Promise;
// create schema
var commentSchema = new Schema({
rating: {
type: Number,
min: 1,
max: 5,
required: true
},
comment: {
type: String,
required: true
},
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
},{
timestamps: true
});
var dishSchema = new Schema({
name: {
type: String,
required: true,
unique: true
},
image:{
type: String,
required: true,
},
category: {
type: String,
required: true,
},
label: String || '',
price: Currency,
description: {
type: String,
required: true
},
comments: [commentSchema]
},{
timestamps: true
});
dishSchema.path('price').get(function(num) {
return (num/100);
});
dishSchema.path('price').set(function(num) {
return (num )
});
// model
var Dishes = mongoose.model('Dish', dishSchema);
module.exports= Dishes;
routers/favRouter:
var express = require('express');
var bodyParser = require('body-parser');
var Verify = require('./verify');
var Favorites = require('../models/favorites');
var favRouter = express.Router();
favRouter.use(bodyParser.json());
favRouter.route('/')
.all(Verify.verifyOrdinaryUser)
.get(function(req, res, next){
Favorites.find({})
.populate(['createdBy', 'dishes'])
.exec(function(err, fav) {
if(err) throw err;
res.json(fav);
});
})
.post(function(req, res, next){
Favorites.create(req.body, function(err, fav){
if(err) throw err;
req.body.createdBy = req.decoded._doc._id;
console.log('Created favorite dish!');
res.json(fav);
});
})
.delete(Verify.verifyOrdinaryUser, Verify.verifyAdmin, function(req, res, next){
Favorites.remove({}, function(err, resp){
if (err) throw err;
res.json(resp);
});
});
favRouter.route('/:objectId ')
.all(Verify.verifyOrdinaryUser)
.get(function(req, res, next){
Favorites.findById(req.params.objectId)
.populate(['createdBy', 'dishes'])
.exec(function(err, fav){
if (err) throw err;
res.json(fav);
});
})
.put(function(req, res, next){
Favorites.findByIdAndUpdate(req.params.objectId, {
$set: req.body
},{
new: true
}, function(err, fav){
if (err) throw err;
// Delete the recent comment then add the new one
fav.id(req.params.objectId).remove();
req.body.createdBy = req.decoded._doc._id;
fav.push(req.body);
fav.save(function(err, fav){
if(err) throw err;
console.log('Updated comments!');
res.json(fav);
});
});
})
.delete(function(req, res, next){
Favorites.findByIdAndRemove(req.params.objectId, function(err, fav){
if (fav.id(req.params.objectId).postedBy != req.decoded._doc._id) {
var err = new Error('You are not authorized to perform this operation!');
err.status = 403;
return next(err);
}
fav.id(req.params.objectId).remove();
fav.save(function(err, resp){
if(err) throw err;
res.json(resp)
})
});
});
module.exports = favRouter;
routers/dishRouter:
var express = require('express');
var bodyParser = require('body-parser');
var Verify = require('./verify');
var Dishes = require('../models/dishes');
var dishRouter = express.Router();
dishRouter.use(bodyParser.json());
dishRouter.route('/')
.get(Verify.verifyOrdinaryUser, function(req, res, next){
Dishes.find({})
.populate('comments.postedBy')
.exec(function(err, dish) {
if(err) throw err;
res.json(dish);
});
})
.post(Verify.verifyOrdinaryUser, Verify.verifyAdmin, function(req, res, next){
Dishes.create(req.body, function(err, dish){
if(err) throw err;
console.log('Dish created!');
var id = dish._id;
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Added the dish with id: '+ id);
});
})
.delete(Verify.verifyOrdinaryUser, Verify.verifyAdmin, function(req, res, next){
Dishes.remove({}, function(err, resp){
if (err) throw err;
res.json(resp);
});
});
dishRouter.route('/:dishId')
.get(Verify.verifyOrdinaryUser, function(req, res, next){
Dishes.findById(req.params.dishId)
.populate('comments.postedBy')
.exec( function(err, dish){
if (err) throw err;
res.json(dish);
})
})
.put(Verify.verifyOrdinaryUser, Verify.verifyAdmin, function(req, res, next){
Dishes.findByIdAndUpdate(req.params.dishId, {
$set: req.body
},{
new: true
}, function(err, dish){
if(err) throw err;
res.json(dish);
})
})
.delete(Verify.verifyOrdinaryUser, Verify.verifyAdmin, function(req, res, next){
Dishes.findByIdAndRemove(req.params.dishId, function(err, resp){
if(err) throw err;
res.json(resp)
});
});
// Comments
dishRouter.route('/:dishId/comments')
.all(Verify.verifyOrdinaryUser)
.get(function(req, res, next){
Dishes.findById(req.params.dishId)
.populate('comments.postedBy')
.exec(function(err, dish) {
if(err) throw err;
res.json(dish.comments);
});
})
.post(function(req, res, next){
Dishes.findById(req.params.dishId, function(err, dish){
if(err) throw err;
req.body.postedBy = req.decoded._doc._id;
dish.comments.push(req.body);
dish.save(function(err, dish){
if(err) throw err;
console.log('Updated comments !');
res.json(dish);
});
});
})
.delete(Verify.verifyAdmin, function(req, res, next){
Dishes.findById(req.params.dishId, function(err, dish){
if (err) throw err;
for (var i = (dish.comments.length -1); i>= 0; i--){
dish.comments.id(dish.comments[i]._id).remove();
}
dish.save(function(err, dish){
if (err) throw err;
res.writeHead(200,{'Content-Type': 'text/plain'});
res.end('Deleted all comments');
});
});
});
dishRouter.route('/:dishId/comments/:commentId')
.all(Verify.verifyOrdinaryUser)
.get(function(req, res, next){
Dishes.findById(req.params.dishId)
.populate('comments.postedBy')
.exec(function(err, dish){
if (err) throw err;
res.json(dish.comments.id(req.params.commentId));
});
})
.put(function(req, res, next){
Dishes.findById(req.params.dishId, function(err, dish){
if (err) throw err;
// Delete the recent comment then add the new one
dish.comments.id(req.params.commentId).remove();
req.body.postedBy = req.decoded._doc._id;
dish.comments.push(req.body);
dish.save(function(err, dish){
if(err) throw err;
console.log('Updated comments!');
res.json(dish);
});
});
})
.delete(function(req, res, next){
Dishes.findById(req.params.dishId, function(err, dish){
if (dish.comments.id(req.params.commentId).postedBy != req.decoded._doc._id) {
var err = new Error('You are not authorized to perform this operation!');
err.status = 403;
return next(err);
}
dish.comments.id(req.params.commentId).remove();
dish.save(function(err, resp){
if(err) throw err;
res.json(resp)
})
});
});
module.exports = dishRouter;

passportjs user object does not return password for compare password

I have an issue that I am not getting an idea that why user stored object does not return password in validatePassword function in model/user.js. I followed all steps described in passportjs official documentation.
I used localstategy of passportjs for signin. When I compare email it always compare but when I tried to execute validate password and use this.password or as a argument it always blank and that is why my password is not compare.
I got all user schema information but I does not get password in user object so I am not able to compare it.
Can anyone tell how could I get out of this issue?
Console Log
root#wk11:/var/www/html/mytripmean/trunk# nodejs server.js
Mytrip is listening on port 1000
MongoDB connection successful
---- User Information ----
myemail#gmail.com
Password##123
{ message: 'Incorrect password.' }
not user:
false
[Error: Illegal arguments: string, undefined]
/var/www/html/mytripmean/trunk/app/data/models/user.js:105
throw err;
^
Error: Illegal arguments: string, undefined
at Error (<anonymous>)
at Object.bcrypt.compare (/var/www/html/mytripmean/trunk/node_modules/bcryptjs/dist/bcrypt.js:250:42)
at model.userSchema.methods.validPassword (/var/www/html/mytripmean/trunk/app/data/models/user.js:102:12)
at Query.<anonymous> (/var/www/html/mytripmean/trunk/app/data/routes/user.js:222:27)
at /var/www/html/mytripmean/trunk/node_modules/kareem/index.js:177:19
at /var/www/html/mytripmean/trunk/node_modules/kareem/index.js:109:16
at process._tickCallback (node.js:448:13)
models/user.js
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId
, randtoken = require('rand-token')
, bcrypt = require("bcryptjs");
var userSchema = new Schema({
// _Id: objectId,
social_id: {
type: String, //(Social id of facebook/twitter)
required: false,
unique: false
},
social_media: {
type: String, //(facebook/twitter)
required: false,
unique: false
},
link_id: {
type: String, //will be dispalying as user reference in url
required: true,
unique: true
},
nick_name: {
type: String, // Unique Nickname for signup
required: true,
unique: true
},
email: {
type: String, // Unqiue Email for signup
required: true,
unique: true
},
password: {
type: String, // Password
required: true,
select: false
},
user_type: {
type: Number, // 1: SuperAdmin, 2: Admin, 3: SiteUser, 4: Restaurant
required: true
}, //reason_to_close: String, // Close Account
is_active: {
type: Number, // -1: pending to activation, 0: inactive, 1: active,
required: true
},
is_close: {
type: Number, // -1: pending to close/Undecided, 0: closed , 1: open/ not close,
required: true
},
is_online: {
type: Number, // 0: Offline, 1: Online
required: true
},
created_at: {
type: Date,
default: Date.now
}, // Registration date
updated_at: {
type: Date, // Registration activation date / user update date
default: Date.now
}
}, {collection: 'user'});
// Password verification
userSchema.methods.validPassword = function (candidatePassword, callback) {
bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
console.log(err);
if (err) {
throw err;
}
callback(null, isMatch);
});
};
var User = module.exports = mongoose.model("User", userSchema);
module.exports.checkEmail = function (callback) {
return this.model('User').count({email: this.email}, callback);
};
module.exports.validateEmailOrNickname = function (username, callback) {
var orCondition = [{nick_name: username}, {email: username}];
//return this.model("user").findOne().or(orCondition);
return this.model("User").find({$or: orCondition}, callback);
};
module.exports.getUserById = function (id) {
User.findById(id, callback);
};
module.exports.createUser = function (user, callback) {
bcrypt.genSalt(10, function (err, salt) {
bcrypt.hash(user.password, salt, function (err, hash) {
user.password = hash;
user.save(callback);
});
});
};
routes/user.js
var express = require('express');
var router = express.Router();
var bcrypt = require("bcryptjs")
var User = require('../models/user');
var UserProfile = require('../models/userProfile');
var UserSignupToken = require('../models/userSignupToken.js');
var IpLogger = require('../models/ipLogger.js');
var passport = require("passport");
var localStrategy = require("passport-local"), Startegy;
router
.route('/api/user/register')
.post(
function (req, res, next) {
var user_, userData_;
userData_ = {
link_id: req.body.manLinkId,
nick_name: req.body.txtNickname,
email: req.body.txtEmail,
password: req.body.manPassword,
user_type: req.body.manUserType,
is_active: req.body.manIsActive,
is_close: req.body.manIsClose,
is_online: req.body.manIsOnline
};
user_ = new User(userData_);
user_.validate(function (err) {
if (err) {
} else {
//check recaptch is validate or not
var request = require('request');
request
.post({
url: 'http://www.google.com/recaptcha/api/verify',
form: {
privatekey: process.env.RECAPTCHA_PRIVATE_KEY,
remoteip: req.connection.remoteAddress,
challenge: req.body.captcha.challenge,
response: req.body.captcha.response
}
}, function (err, httpResponse, body) {
if (body.match(/false/) === null) {
//Recaptcha validated
User.createUser(user_, function (err, data) {
if (err) {
console.log("stpe 1:");
console.log(err);
res.json({status: 0, message: 'User having an error on stage 1'});
} else {
res.locals.user = data;
//res.json({error:1, message: 'User saved'});
next();
}
});
//res.json({ "captchaError": true });
} else {
res.json({"captchaError": false});
}
});
}
});
},
function (req, res, next) {
var userProfileData_, userProfile_;
userProfileData_ = {
user_id: res.locals.user.id,
link_id: res.locals.user.link_id,
full_name: req.body.txtFullname,
is_active: -1
};
userProfile_ = new UserProfile(userProfileData_);
userProfile_.save(function (err, data) {
if (err) {
console.log("stpe 2:");
console.log(err);
res.json({status: 0, message: 'User having an error on stage 2'});
} else {
//res.json({error:1, message: 'User profile generated'});
next();
}
});
},
function (req, res, next) {
var userSignupTokenData_, userSignupToken_;
userSignupTokenData_ = {
user_id: res.locals.user.id,
link_id: res.locals.user.link_id,
is_active: -1
};
userSignupToken_ = new UserSignupToken(userSignupTokenData_);
userSignupToken_.save(function (err, data) {
if (err) {
console.log("stpe 3:");
console.log(err);
res.json({status: 0, message: 'User having an error on stage 3'});
} else {
//res.json({error:1, message: 'User signup token generated'});
next();
}
});
},
function (req, res, next) {
var ipLoggerData_, ipLogger_, client_IP;
ipLoggerData_ = {
user_id: res.locals.user.id,
link_id: res.locals.user.link_id,
client_ip: req.ip,
activity: "signup"
};
ipLogger_ = new IpLogger(ipLoggerData_);
ipLogger_.save(function (err, data) {
if (err) {
console.log("stpe 4:");
console.log(err);
res.json({status: 0, message: 'User having an error on stage 4'});
} else {
res.json({status: 1, message: 'user saved'});
}
});
}
);
//Check unique validation
router
.route('/api/user/authenticate')
.post(
function (req, res, next) {
console.log("---- User Information ----");
console.log(req.body.txtSigninEmail);
console.log(req.body.txtSigninPassword);
passport.authenticate('local', function (err, user, info) {
console.log(info);
if (err) {
console.log(err);
return next(err);
}
if (!user) {
console.log("not user:");
console.log(user);
return res.status(401).json({
err: info
});
}
req.login(user, function (err) {
if (err) {
return res.status(500).json({
err: 'could not login user'
});
}
res.status(200).json({
status: 'login successful'
});
});
})(req, res, next);
});
router
.route('/api/user/checkEmail')
.post(
function (req, res) {
User.count({email: req.body.txtSigninPassword}, function (err, user) {
if (err) {
// console.log("error false");
res.json(false);
} else {
// console.log("data");
// console.log(user);
res.json({"status": user > 0 ? false : true});
}
});
});
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
passport.use('local', new localStrategy(
{
usernameField: 'txtSigninEmail',
passwordField: 'txtSigninPassword'
},
function (username, password, done) {
User.findOne({email: username}, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {message: 'Incorrect username.'});
}
if (!user.validPassword(password)) {
return done(null, false, {message: 'Incorrect password.'});
}
return done(null, user);
});
}
));
module.exports = router;
After 2 hours of efforts I found answer of my question. In my User model password field, I set property "select:false", due to that I always get a password as blank.
Older:
var userSchema = new Schema({
password: {
type: String, // Password
required: true,
select: false
},
}
After re-setting select: true it works fine.
Updated:
var userSchema = new Schema({
password: {
type: String, // Password
required: true,
select: true
},
}

i want to use async and upsert along with sequelize transaction

upsertAsync: function(req, res, next) {
var datas = req.body;
var user = req.body.user;
async.each(datas, function(data, cb) {
sequelize().transaction({
autocommit: true
}, function(t) {
models.Customer.upsert({
id: data.id,
code: data.code,
createdBy: user.name,
modifiedBy: user.name
}, {
transaction: t
}).then(function(customer) {
cb();
}).
catch (function(error) {
t.rollback();
res.status(500).json(error);
});
}, function(err, data) {
log.debug('error (upsertAsync)', err);
if (err) {
t.rollback();
res.status(500).json(err);
}
t.commit();
res.json({
responseCode: '200',
message: 'Customer has been created..!',
data: data
});
});
});
},
I'm using async.each to insert data into sqlite database at the same time. I want to rollback if any error occurs but it shows error which is [TypeError: Cannot set property 'options' of undefined

mongoose and node js insert/post data

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);
}

Resources