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.
Related
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');
});
});
}
I'm teaching myself Mongodb. At first, I ran npm install --save mongoose uuid in Terminal to start things off. The goal of my program is to store a user in the database.
In Terminal, after running node index.js I want it to say:
About to save!
Saved!
But what I'm seeing in Terminal is (below):
Here's index.js
var mongoose = require('mongoose');
var uuid = require('uuid');
var Schema = mongoose.Schema;
/* New code from suggested website in error */
var promise = mongoose.connect('mongodb://localhost:testMongo/testMongo', {
useMongoClient: true,
});
promise.then(function(db) {
db.model();
connection.openUri('mongodb://localhost:testMongo/testMongo', { /* options */ });
var userSchema = new Schema({
email: {
type: String,
unique: true
},
password: {type: String},
todos: [
{
text: {type: String}
}
]
});
userSchema.pre('save', function(next) {
console.log("About to save!");
var user = this;
user.password = uuid.v4();
next();
});
var User = mongoose.model('user', userSchema);
var email = 'test#test.com';
// var user = new User({
// email: email
// });
//
// user.save(function(err) {
// if(err) {
// return console.log(err);
// } else {
// return console.log("User was saved!");
// }
// })
//
// console.log("Outside of callback!");
var text = "This is a todo.";
User.findOne({email: email}, function(user, err) {
if(err) {
return console.log(err);
}
if(!user) {
return console.log("Couldn't find user!");
}
var count = user.todos.push({
text: text
});
console.log(count);
user.save(function(err){
if(err) {
console.log(err);
} else {
console.log("Saved!");
}
});
});
Error in Terminal:
(node:14312) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
{ _id: 595fe7c14a9810330c75aacc,
password: '297d5907-d9d7-49ef-800c-97a56aa395f7',
email: 'test#test.com',
__v: 0,
todos: [] }
That is not an error. It clearly says it's a warning: DeprecationWarning.
Also the message gives you a link to resolve the warning: http://mongoosejs.com/docs/connections.html#use-mongo-client
This is my mongoose schema for work:
var mongoose = require('mongoose');
var WorkSchema = mongoose.Schema({
Title:{
type:String,
required:true,
unique:true
},
VideoURL:String,
Image: { data: Buffer, contentType: String },
Price:Number,
Username:String,
Company_id:[{type:mongoose.Schema.Types.ObjectId, ref:'Company'}]
});
var Work = module.exports = mongoose.model("Work", WorkSchema);
And this is the my work controller:
let Work = require('../Models/Work');
let Company = require('../Models/Company');
let WorkController = {
createWork:function(req, res){
let trial = new Work();
console.log( req.session.Username+ " session");
trial.Username= req.session.Username;
trial.VideoURl= req.body.VideoURl;
trial.Price=req.body.Price;
trial.Title= req.body.Title;
User=req.session.Username;
Company.findOne( {Username:User},function(err, company){
trial.Company_id=company._id;
trial.save(function(err, Work){
if(err){
res.send(err.message);
console.log(err);
}
});
});
}
}
module.exports = WorkController;
And this is my schema for Company:
let Company = require('../Models/Company');
let CompanyController = {
login:function(req,res){
var Username = req.body.Username;
var Password =req.body.Password;
Company.findOne({Username:Username,Password:Password},function(err,Company)
{
if(!Company){
return console.log('you are not athorized ');
res.status(500).send(errorMsg);
;}
else{
res.json(Company);
req.session.Username = Company.Username;
console.log("username session: " + req.session.Username);
}
})
}
,
createCompany:function(req, res){
let company = new Company(req.body);
company.save(function(err, company){
if(err){
res.send(err.message)
console.log(err);
}
else{
req.session.Username= req.body.Username;
console.log(company);
}
})
}
}
module.exports = CompanyController;
When the the company user logs in and tries to create work, this error appears in the console "TypeError: Cannot read property 'id' of null"
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);
})
});
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