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"
Related
How can I make a method in which if a user sign up that user get a 4 digit id? And that id increases whenever new user signup?
In NodeJS that id should be random but it should be at least 4 digit and it move on & on whenever a new user sign up but the minimum value should be 4 digit only so how can I built that method? if its a large process than please explain me I will get a idea or if its easy and it can be done in less lines of code than please provide snippets of that example you can check my code
user.controller:
const user_module = require('./user.modules');
class user_controller extends user_module {
static create_user = async (req, res) =>{
try {
console.log("controller response",req.body)
let response = await this.save_user_details(req)
let message = 'Success';
res.send({
sucess: true,
message: message,
data: response
})
} catch (error) {
let status_code = error.status.code != undefined ? error.status_code: 500;
let type = error.type != undefined ? err.type: 'Bad Request';
let message = err.custom_msg != undefined ? error.custom_msg: "Something went wrong"
res.status(status_code).send({
sucess: false,
error:type,
message: message
})
}
}
static get_users = async (req, res) =>{
try {
console.log("controller response",req.body)
let response = await this.retrieve_user(req)
let message = 'Success';
res.send({
sucess: true,
message: message,
data: response
})
} catch (error) {
let status_code = error.status.code != undefined ? error.status_code: 500;
let type = error.type != undefined ? err.type: 'Bad Request';
let message = err.custom_msg != undefined ? error.custom_msg: "Something went wrong"
res.status(status_code).send({
sucess: false,
error:type,
message: message
})
}
}
static otp_verify = async (req, res) =>{
try {
console.log("controller response",req.body)
let response = await this.verify_user(req)
if(response.status){
res.send({
success: true,
message: response.message,
data: response.user
})
}else{
res.status(400).send({
success: false,
error: false,
message: response.message
})
}
} catch (error) {
let status_code = error.status_code != undefined ? error.status_code: 500;
let type = error.type != undefined ? err.type: 'Bad Request';
let message = error.custom_msg != undefined ? error.custom_msg: "Something went wrong"
res.status(status_code).send({
sucess: false,
error:type,
message:message
})
res.end();
}
}
}
module.exports = user_controller
user.modules:
const models = require('../models');
class user_module {
static save_user_details = async (req) => {
try {
console.log("req body", req.body)
const { profileImage } = req.body
let set_data = req.body
if (!!profileImage) {
set_data.profileImage = profileImage
}
return await models.users.create(set_data)
} catch (error) {
throw error
}
}
static retrieve_user = async (req) => {
try {
let {limit, pagination} = req.query
let query = {}
let projection ={__v: 0}
let options = {
lean: true,
sort: {_id: -1},
skip: !Number(pagination) ? 0: Number(pagination) * !Number(limit) ? 10: Number(limit),
limit: !Number(limit) ? 10: Number(limit)
}
let users = await models.users.find(query, projection, options)
let count = await models.users.count(query)
return {users, count}
} catch (error) {
throw error
}
}
static verify_user = async (req) => {
try {
console.log("req body", req.body)
const { otp, user_id } = req.body
if(otp == '123456'){
let user = await models.users.findById(user_id)
return {user: user, status: true, message: 'success'}
}else{
return {user: null, status: false, message: 'Otp Invalid'}
}
} catch (error) {
throw error
}
}
}
module.exports = user_module
Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Users = new Schema({
name: String,
phoneNumber: String,
userid: String,
profileImage: {
type: String,
default: 'https://www.pngitem.com/pimgs/m/146-1468479_my-profile-icon-blank-profile-picture-circle-hd.png'
},
about: String,
selectedCountry: {
type: Object
}
})
module.exports = mongoose.model("users", Users)
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
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
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.