Populate mongoose on 3 schema - javascript

I am trying to populate Schema. I have successfully populate 2 schema. But I have a hard time/understanding on populating 3 schema.
these are my schema
member schema
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var Schema = mongoose.Schema;
var MemberSchema = new mongoose.Schema({
full_name : {
type: String
},
current_position : {
type: String
},
position: {
type: String
},
dateStarted : {
type: String
},
is_admin: {
type: Boolean,
default : false
},
team : {
type: Schema.Types.ObjectId,
ref: 'Team'
},
account : {
type: Schema.Types.ObjectId,
ref : 'Accounts'
}
});
var Members = module.exports = mongoose.model('Members', MemberSchema);
module.exports.createMember = function(newMember, callback){
newMember.save(function(err){
if (err) throw err;
});
}
account schema
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var Schema = mongoose.Schema;
var Team = require('../model/team');
var AccountSchema = mongoose.Schema({
account_name:{
type: String,
index:true
},
account_type:{
type: String
},
website_url:{
type: String
},
description:{
type: String
},
account_owner:{
type: String
},
phone_number:{
type: String
},
industry:{
type: String
}
});
var accounts = module.exports = mongoose.model('Accounts', AccountSchema);
module.exports.createAccount = function(newUser, callback){
newUser.save(function(err){
if (err) throw err;
});
}
team schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var TeamSchema = new mongoose.Schema({
team_name : {
type: String
},
dateCreated : {
type : Date,
default:function(){
return Date.now();
}
}
});
var Team = module.exports = mongoose.model('Team', TeamSchema);
module.exports.createTeam = function(newTeam, callback){
newTeam.save(function(err,teamObj){
if (err) throw err;
if(teamObj){
if(typeof callback == 'function'){
callback(null, teamObj._id);
}
}
});
}
and this is wnat i already populate, the team schema and member schema
[
{
"_id": "587f276edebe7725c48e7286",
"full_name": "joel ralph balignasay",
"position": "Web Developer",
"dateStarted": "Nov 15 2016",
"team": {
"_id": "587f25a98a583e1954908832",
"team_name": "Web Team",
"__v": 0,
"dateCreated": "2017-01-18T08:22:01.541Z"
},
"account": "587f210d7729b13554901cf4",
"__v": 0,
"is_admin": false
}
]
this is my function
app.get('/admin/accounts/show_team/api/merge', function(req,res){
var team_id = '587f25a98a583e1954908832';
var account_id = '587f210d7729b13554901cf4';
MemberModel.find({}).populate('team').exec(function(err,member){
Accounts.find({}).populate('account').exec(function(err,acount){
if (err) {
console.log(err)
} else {
res.json(member);
}
});
});
});
Thanks. I just want to know how to insert the account schema.
Thanks again

I already found a way this is my updated function
app.get('/admin/accounts/show_team/api/merge', function(req,res){
var team_id = '587f25a98a583e1954908832';
var account_id = '587f210d7729b13554901cf4';
var member_id = '587f276edebe7725c48e7286';
MemberModel.findById(member_id)
.populate('team')
.populate('account')
.exec(function(err,results){
res.send(results);
})
});

You can even limit the fields you want after population, like this
app.get('/admin/accounts/show_team/api/merge', function(req,res){
var team_id = '587f25a98a583e1954908832';
var account_id = '587f210d7729b13554901cf4';
var member_id = '587f276edebe7725c48e7286';
MemberModel.findById(member_id)
.populate('team', 'teamField1, teamField2, teamField3..')
.populate('account', 'accountField1, accountField2...')
.exec(function(err,results){
res.send(results);
})
});
_id always comes by default.
If you only want _id, do this
app.get('/admin/accounts/show_team/api/merge', function(req,res){
var team_id = '587f25a98a583e1954908832';
var account_id = '587f210d7729b13554901cf4';
var member_id = '587f276edebe7725c48e7286';
MemberModel.findById(member_id)
.populate('team', '_id')
.populate('account', '_id')
.exec(function(err,results){
res.send(results);
})
});

Related

Adding an object to an array in a sub-document in mongoose, mongodb. Property 'messages` could not be found

I have four models: teacher, student, teacherMessageSchema,studentMessageSchema. teacherMessageSchema is a subdocument in the 'teacher model in the messages: [teacherMessageSchema] property, and studentMessageSchemais a subdocument in thestudent model in the messages: [studentMessageSchema] property. How to add an object to arrays[teacherMessageSchema]and[studentMessageSchema]`. I tried to do this like this:
module.exports.sendMessage = (req, res) => {
let {sender, receiver, msg} = req.body;
var hex = /[0-9A-Fa-f]{6}/g;
sender = (hex.test(sender))? mongoose.Types.ObjectId(sender) : sender;
receiver = (hex.test(receiver))? mongoose.Types.ObjectId(receiver) : receiver;
Teacher.findById({_id: receiver}, function(err, member) {
console.log(member, 'member');
member.messages.push({msg});
console.log('messages', member.messages)
member.save(function(err, updated) {
if (err)
res.send(err);
res.json(updated, 'updated');
});
});
}
But the property messages cannot be found.
teacher and student model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const crypto = require('crypto');
const {studentMessageSchema, teacherMessageSchema} = require('./message');
const userSchema = new Schema({
name: {
type: String,
trim: true,
required: true,
maxLength: 32
},
email: {
type: String,
unique: true,
trim: true,
required: true,
lowercase: true
}
}, {timestamps: true});
const studentSchema = userSchema.clone();
studentSchema.add({
messages : [studentMessageSchema]
});
const teacherSchema = userSchema.clone();
teacherSchema.add({
messages : [teacherMessageSchema]
});
const User = mongoose.model('User', userSchema);
const Student = mongoose.model('Student', studentSchema);
const Teacher = mongoose.model('Teacher', teacherSchema);
module.exports = {
User,
Student,
Teacher
}
message model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const messageSchema = new Schema({
"contentInfo" : {
"viewed" : {type: Boolean, default: false},
"msg" : {type: String, required: true},
"createdAt" : { type : Date, default: Date.now }
}
});
const studentMessageSchema = messageSchema.clone();
studentMessageSchema.add({
"receiver" : {
type: Schema.ObjectId
}
});
const teacherMessageSchema = messageSchema.clone();
teacherMessageSchema.add({
"sender" : {
type: Schema.ObjectId
}
});
module.exports = {
messageSchema,
teacherMessageSchema,
studentMessageSchema
}
controller message
const User = require('../models/user');
const Student = require('../models/user');
const Teacher = require('../models/user');
const mongoose = require('mongoose');
module.exports.sendMessage = (req, res) => {
let {sender, receiver, msg} = req.body;
var hex = /[0-9A-Fa-f]{6}/g;
sender = (hex.test(sender))? mongoose.Types.ObjectId(sender) : sender;
receiver = (hex.test(receiver))? mongoose.Types.ObjectId(receiver) : receiver;
Teacher.findById({_id: receiver}, function(err, member) {
console.log(member, 'member');
member.messages.push({msg});
console.log('messages', member.messages)
member.save(function(err, updated) {
if (err)
res.send(err);
res.json(updated, 'updated');
});
});
}
before push msg you must to create message model, after that push it to user.messages
let {studentMessageSchema}= require("path of messeages Schema/")
module.exports.sendMessage = (req, res) => {
let {sender, receiver, msg} = req.body;
var hex = /[0-9A-Fa-f]{6}/g;
sender = (hex.test(sender))? mongoose.Types.ObjectId(sender) : sender;
receiver = (hex.test(receiver))? mongoose.Types.ObjectId(receiver) : receiver;
//create a studentMessage Model
let studentMessage = new studentMessageSchema({
contentInfo : {
msg : msg
},
receiver : receiver
})
Teacher.findById({_id: receiver}, function(err, member) {
console.log(member, 'member');
member.messages.push({studentMessage });
console.log('messages', member.messages)
member.save(function(err, updated) {
if (err)
res.send(err);
res.json(updated, 'updated');
});
});
}

how to delete referenced value in mongoose schema

const UniversitySchema = new Schema({
university_name: {
type:String,
},
status: {
type: String
}
});
const CollageSchema = new Schema({
collage_name: {
type:String,
required: [true,'Name field is required']
},
university_id: {
type: [{ type: Schema.Types.ObjectId ,
ref: 'university' }]
},
type: {
type:String
}
});
router.delete('/university/:id',function(req,res,next){
University.findByIdAndRemove({_id:req.params.id}).then(function(detail){
res.send(detail);
});
});
I have referenced _id of UniversitySchema in CollageSchema and if I delete any university corresponding collage should be deleted. How to do this?
With an additional mongo call on collages collection, using Promise.all() :
router.delete('/university/:id',function(req,res,next){
const ObjectId = require('mongodb').ObjectId;
const _id = ObjectId(req.params.id);
const removeUniversity = University.findByIdAndRemove({ _id: _id });
const removeCollage = Collage.remove({ university_id: _id });
Promise
.all([removeUniversity, removeCollage])
.then(function(values) {
const detail = values[0];
res.send(detail);
})
.catch((err) => console.error(err));
});

How to add each result of the last loop within two nested searches in an array to show the full result in NodeJS and Mongoose?

I'm a beginner in both Stackoverflow and NodeJS/Mongoose, I'm sorry if I have an error or break a rule. Thank you in advance.
I need a function that it return all the nearby products there are in my location, this is given through the user wich "id" is a request called "user".
I try making this function, where finalProducts return all the products that they exit at the search, but when I try to add as component of result body finalProducts return data empty.
The error is the following:
throw er; // Unhandled 'error' event
^
Error: Can't set headers after they are sent.
at ServerResponse.setHeader (_http_outgoing.js:371:11)
at ServerResponse.header (/home/frangaliana/Escritorio/client-thingy/node_modules/express/lib/response.js:730:10)
at ServerResponse.send (/home/frangaliana/Escritorio/client-thingy/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/home/frangaliana/Escritorio/client-thingy/node_modules/express/lib/response.js:256:15)
at ServerResponse.send (/home/frangaliana/Escritorio/client-thingy/node_modules/express/lib/response.js:158:21)
at /home/frangaliana/Escritorio/client-thingy/controllers/product.js:200:41
at /home/frangaliana/Escritorio/client-thingy/node_modules/mongoose/lib/query.js:2916:18
at newTickHandler (/home/frangaliana/Escritorio/client-thingy/node_modules/mpromise/lib/promise.js:234:18)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
I show the code and the models for help to understand the trouble:
Function that search nearby products in controller product.js:
function getNearbyProducts(req, res) {
let userId = req.user;
let point;
var geoOptions = {
spherical: true,
maxDistance: 500
}
User.findById(userId, {password:0})
.populate('location','coordinates')
.exec(function (err, result) {
if (err) console.log('No se ha podido encontrar la localización')
point = {
type: "Point",
coordinates: [parseFloat(result.location.coordinates[0]),parseFloat(result.location.coordinates[1])]
}
Location.geoNear(point,geoOptions, function(err, resultLocations) {
for(var i = resultLocations.length - 1 ; i >= 0 ; i--){
var nearLocation = resultLocations[i].obj.id
var queryUser = {"location": nearLocation}
User.find(queryUser)
.exec(function (err, resultUsers) {
for(var j = resultUsers.length - 1 ; j >= 0; j--) {
if(resultUsers[j] !== undefined){
var exactUser = resultUsers[j].id
var limit;
if(req.query.limit) {
limit = parseInt(req.query.limit)
if(isNaN(limit)){
return next(new Error())
}
} else {
limit = 10;
}
var queryProduct = {"user": exactUser}
if(req.query.before) {
queryProduct = {"user": exactUser, "_id" : {$lt: req.query.before}};
}else if (req.query.after) {
queryProduct = {"user": exactUser, "_id" : {$gt: req.query.after}};
}
Product.find(queryProduct)
.limit(limit)
.populate('user')
.exec(function (err, resultProducts) {
var finalProducts = [];
for(var k = resultProducts.length - 1 ; k >= 0; k--){
if(resultProducts[k] !== undefined){
finalProducts.push(resultProducts[k])
}
}
if(finalProducts.length > 0){
if(req.query.before){
products.reverse();
}
var finalResult = {
data: finalProducts,
paging: {
cursors: {
before: finalProducts[0].id,
after: finalProducts[finalProducts.length-1].id
},
previous: 'localhost:3000/api/products?before='+finalProducts[0].id,
next: 'localhost:3000/api/products?after='+finalProducts[finalProducts.length-1].id,
},
links: {
self: 'localhost:3000/api/products',
users: 'localhost:3000/api/users'
}
}
} else {
var finalResult = {
data: finalProducts,
paging: {
cursors: {
before:undefined,
after:undefined
},
previous: undefined,
next: undefined
},
links: {
self: 'localhost:3000/api/products',
users: 'localhost:3000/api/users'
}
}
}
res.status(200).send(finalResult);
})
}
}
})
}
})
})
})
Models:
user.js
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs');
const Location = require('../models/location');
const crypto = require('crypto');
const UserSchema = new Schema({
email: {
type: String,
lowercase: true,
//Añadir campo unique: true para que sólo se pueda registrar un email
},
name: String,
password: String,
userimg: String,
gender: Boolean,
birthdate: Date,
signUpDate: {
type: Date,
default: Date.now(),
},
location:{
type: Schema.ObjectId,
ref: 'Location'
}
});
UserSchema.pre('save', function(next) {
let user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(10, (err, salt) => {
if (err) return next(err);
bcrypt.hash(user.password, salt, null, (err, hash) => {
if (err) return next(err);
user.password = hash;
next();
});
});
});
UserSchema.methods.gravatar = function() {
if(!this.email) return `https://gravatar.com/avatar/?s=200&d=retro`
const md5 = crypto.createHash('md5').update(this.email).digest('hex')
return `https://gravatar.com/avatar/${md5}?s=200&d=retro`
}
module.exports = mongoose.model('User', UserSchema);
product.js
'use strict'
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const User = require('../models/user');
var max = [5 , 'The value of ({VALUE}) exceeds the limit ({MAX}). ']
var min = [1 , 'The value of ({VALUE}) is beneath the limit ({MIN}). ']
const ProductSchema = Schema({
title: String,
price: {
type: Number,
default: 0
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
categoryproduct: {
type: String,
enum:['Moda y Accesorios', 'Motor', 'Electrónica', 'Deporte', 'Libros, Música y Películas', 'Electrodomésticos', 'Servicios', 'Muebles y Decoración', 'Otros'],
default: 'Electrónica'
},
description: {
type: String,
default: 'Objeto para vender'
},
visits: {
type: Number,
default: 0
},
status: {
type: Boolean,
default: false
},
publicationdate: {
type: Date,
default: Date.now()
},
salesrating: {
type: Number,
max: max,
min: min,
default: 1
},
salescomment: {
type: String,
default: 'Perfecto'
}
})
module.exports = mongoose.model('Product', ProductSchema);
location.js
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const LocationSchema = new Schema({
type: {
type: String,
default: "Point"
},
coordinates: {
type: [Number],
index: "2dsphere",
default: [38.280153, -0.712901]
}
})
module.exports = mongoose.model('Location', LocationSchema);
I hope this question can be resolved or at least someone explain me because it doesn't work well. A lot of thanks again!
EDIT: (Because I have fix the problem)
Thanks to skirtle who gave me the idea to solve this.
I didn't control the asynchronous calls that threw the searches with Mongoose and that generated multiple responses, so as he told me I started using Promises to keep track of them when the result was throwing me an array of id's whether they were from User, Location or Product I treated them one by one.
I recalled that a Mongoose query could be accompanied by a filter {$in:[array]} that returned all results containing any of these id's (in my case) that had the array looking like this:
function getNearbyProducts(req, res) {
var userId = req.user;
var promiseUser = User.findById(userId, {password: 0})
.populate('location')
.exec()
promiseUser
.then(function(result){
return result.location;
})
.then( function(resultUser){
return Location.geoNear(
{type:'Point', coordinates: [parseFloat(resultUser.coordinates[0]),parseFloat(resultUser.coordinates[1])]},
{maxDistance:100000, spherical: true}
).then(function(locsGeoNear){
var resultGeoNear = []
for(var i = locsGeoNear.length - 1; i >= 0; i--){
if(resultUser.id != locsGeoNear[i].obj.id){
resultGeoNear.push(locsGeoNear[i].obj.id)
}
}
return resultGeoNear
})
})
.then(function(resultSearchLocs){
var queryUsersByLocation = {'location': {$in: resultSearchLocs}}
return User.find(queryUsersByLocation, {password: 0})
.exec()
.then(function(usersSearchs){
var resultUsers = []
for(var i = usersSearchs.length - 1; i >= 0; i--){
if(userId != usersSearchs[i].id){
resultUsers.push(usersSearchs[i].id)
}
}
return resultUsers
})
})
.then(function(resultSearchUsers){
var limit;
if(req.query.limit) {
limit = parseInt(req.query.limit)
if(isNaN(limit)){
return next(new Error())
}
} else {
limit = 10;
}
var queryProductsByUsers = {'user': {$in: resultSearchUsers}}
//Para obtener la página anterior a un id
if (req.query.before) {
queryProductsByUsers = {'user': {$in: resultSearchUsers}, "_id" : {$lt: req.query.before}};
//Para obtener la página posterior a un id
} else if (req.query.after) {
queryProductsByUsers = {'user': {$in: resultSearchUsers}, "_id": {$gt: req.query.after}};
}
return Product.find(queryProductsByUsers)
.limit(limit)
.exec()
})
.then(function(resultSearchProducts){
if(resultSearchProducts.length > 0){
if(req.query.before){
resultSearchProducts.reverse();
}
var resultFinal = {
data: resultSearchProducts,
paging: {
cursors: {
before: resultSearchProducts[0].id,
after: resultSearchProducts[resultSearchProducts.length-1].id
},
previous: 'localhost:3000/api/products?before='+resultSearchProducts[0].id,
next: 'localhost:3000/api/products?after='+resultSearchProducts[resultSearchProducts.length-1].id,
},
links: {
self: 'localhost:3000/api/products',
users: 'localhost:3000/api/users'
}
}
} else {
var resultFinal = {
data: resultSearchProducts,
paging: {
cursors: {
before:undefined,
after:undefined
},
previous: undefined,
next: undefined
},
links: {
self: 'localhost:3000/api/products',
users: 'localhost:3000/api/users'
}
}
}
res.setHeader('Content-Type', 'application/json');
res.status(200).send(resultFinal);
})
.catch(function(err){
console.log(`${err}`)
})
}
Many thanks to the community but above all to skirtle who gave me the keys to reach my solution.
Greetings!
If you add the following logging before you call send:
console.log('sending response');
res.status(200).send(finalResult);
I believe you'll find that you're calling send multiple times on the same request, which isn't allowed. When you call send the first time the request/response is over and any attempt to send more data will result in an error.
I'm struggling to follow the code but I believe the cause is all that looping you're doing. You need to wait until all your DB queries are done and you've gathered your final data before you call send.
You may find Promises a useful way to reduce the complexity in products.js but even if you don't fancy using them I highly recommend a bit of refactoring to make that file intelligible. As a general rule the Pyramid of Doom is a sign that you've got problems https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming)

MongoDB references with Node.js I can not populate

I want to show user's location information on the screen.
For Example:
name: "Andy" surname : "Carol" City : "Istanbul" Town : "Kadıkoy"
When I call the getuser function I want to display the City and Town name.
This is my code:
UserSCHEMA
// Model for the User
module.exports = (function userSchema() {
var Mongoose = require('mongoose');
var Schema = Mongoose.Schema;
var userSchema = new 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
},
lok_id: [{
type: Mongoose.Schema.Types.ObjectId,
ref: 'locations'
}]
});
var collectionName = 'users';
var USERSCHEMA = Mongoose.Schema(userSchema);
var User = Mongoose.model(collectionName, USERSCHEMA);
return User;
})();
USERController
//This Controller deals with all functionalities of User
function userController() {
var User = require('../models/UserSchema');
// Creating New User
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'
});
}
});
};
//Populateeee
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();
Location Schema
//Schema for Location
module.exports = (function LocationSchema() {
var Mongoose = require('mongoose');
var Schema = Mongoose.Schema;
var LocationSchema = new Schema({
userid: {
type: Mongoose.Schema.Types.ObjectId,
ref: 'users'
},
il: {
type: String,
require: true
},
ilce: {
type: String,
require: true
}
});
var collectionName = 'locations';
var LocationSCHEMA = Mongoose.Schema(schema);
var Location = Mongoose.model(collectionName, LocationSCHEMA);
return Location;
})();
Location Controller
//This Controller deals with all functionalities of Location
function locationController() {
var location = require('../models/LocationSchema');
// Creating New Location
this.createLocation = function (req, res, next) {
var userid = req.params.userid;
var il = req.params.il;
var ilce = req.params.ilce;
location.create({
userid: userid,
il: il,
ilce: ilce
}, function (err, result) {
if (err) {
console.log(err);
return res.send({
'error': err
});
} else {
return res.send({
'result': result,
'status': 'successfully saved'
});
}
});
};
// Fetching Details of Location
this.getLocation = function (req, res, next) {
location.find({}, function (err, result) {
if (err) {
console.log(err);
return res.send({
'error': err
});
} else {
console.log(result);
return res.send({
'location Details': result
});
}
});
};
return this;
};
module.exports = new locationController();
I already had a problem with model definition.
It was fixed by adding the third parameter to mongoose.model (the explicit collection name)
// Try to replace :
var collectionName = 'users';
var USERSCHEMA=Mongoose.Schema(userSchema);
var User = Mongoose.model(collectionName, USERSCHEMA);
// with:
var collectionName = 'users';
var USERSCHEMA=Mongoose.Schema(userSchema);
var User = Mongoose.model(collectionName, USERSCHEMA, collectionName);
the collectionName must be set either in the schema definition or in the model definition. for more details see here

NodeJs, Mocha and Mongoose

I have the follow structure:
|server
|db
|mongooseTest.js
|test
|userModel.test.js
|user
|userModel.js
With their code:
mongooseTest.js
var mongoose = require('mongoose');
module.exports = function() {
var db = mongoose.createConnection('localhost', 'dbUnitTest');
db.on('connected', function() {
console.log('DB: ' + db.name + ' local: ' + db.host + ':' + db.port);
});
db.on('error', function(err) {
console.log(err);
});
return db;
};
userModel.test.js
var assert = require('assert'),
should = require('should'),
conn = require('../db/mongooseTest'),
UserModel = require('../user/userModel');
describe('User Model', function() {
describe('Save', function() {
it('Saving...', function() {
var db = conn();
var Model = db.model('User');
var userModel = new Model({
name: 'My Name',
email: 'contact#com.br',
pass: 'anything123'
});
userModel.on('save', function(user) {
console.log('Passed by save event handle from user');
});
userModel.save(function(err, user) {
console.log('Passed by save from user');
if(err) console.log(err);
console.log(user);
});
});
})
})
userModel.js
var mongoose = require('mongoose'),
crypto = require('crypto'),
Schema = mongoose.Schema;
var setPass = function(value) {
var salt = 'anyRandomSaltValue';
this.set('salt', salt);
var pass = hashPass(value + salt);
return pass;
}
var hashPass = function(value) {
return crypto.createHash('sha1').update(value).digest('HEX');
}
var userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
pass: {
type: String,
required: true,
set: setPass
},
salt: {
type: String,
required: true
}
});
userSchema.method({
validatePass: function(senha) {
var salt = this.get('salt');
var passSha = hashPass(senha + salt);
return passSha === this.get('senha');
},
});
userSchema.static({
findByEmail: function(email, success, error) {
this.findOne({
email: email
}, function(e, o) {
if(e) {
if(error) error(e);
} else {
if(success) success(o);
}
});
},
});
module.exports = mongoose.model("User", userSchema);
The problem is...
When I run "mocha" to execute my unit tests, the callback of the save function is not performed.
Thanks for all!
Issue solved with the this approach.
I also found another solution which looks good but I didn'try.

Categories

Resources