hi I wanna see on the screen User all information but I cannot add user in mongodb . User's location information in Locations Schema.But I dont know how to get location information(i.e city,town...) to input UserSchema.This is my codes:
User Schema :
var userSchema = Mongoose.Schema({
name:{type: String,require:true},
surname: {type: String,require:true},
tel: {type: String,require:true},
age: {type: String,require:true},
mevki_id: {type: String,require:true},
location_id: { type: [Mongoose.Schema.Types.ObjectId], ref: 'locations' }
});
Create User Function :
this.createUser = function (req, res, next) {
var lok=new Location({il:req.params.il,ilce:req.params.ilce});
lok.save(function(err){
var user=new User({name:req.params.name,surname:req.params.surname,tel:req.params.tel,age:req.params.age,mevki_id:req.params.mevki_id,location_id:user});
user.save(function(err){
user.location_id=lok;
});
return res.send({})
});
}
Thnks :)
//define this as your schema in your file
var userSchema = new Schema({
name: {type: String, required: true},
surname: {type: String, required: true},
tel: {type: Number, required: true},
age: {type: Number, required: true},
mevki_id: {type: String, required: true},
location_id:{type:String,required:true}
});
var CollectionModel_user = conn.model('users', userSchema)
return function (req, res, next) {
req.Collection_user = CollectionModel_user;
next();
}
// create a route which can create a route in your
// app.js or main.js file that will create a new
// collection in your mongo.
router.all('/user/create', function (req, res) {
var create = req.Collection_user;
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 location_id = req.body.location_id;
var record = new create({
name: name,
surname: surname,
tel: tel,
age: age,
mevki_id: mevki_id,
location_id: location_id
});
if (name.length > 0) {
record.save(function (err, result) {
if (err) {
res.json({status: 0, message: err})
} else {
res.json({status: 1, message: " success"});
}
})
} else {
res.json({status: 0, msg: "Invalid Fields"});
}
});
Related
I am trying to use MongoDB collections and relate one collection to another. I have one collection named "player" and one named "calendar", and I am trying to add player info to calendar events so only the player logged into the system can see their specific events.
I can see all the info of the event when I console log req.body:
{ start_date: '2019-02-09 00:00',
end_date: '2019-02-09 00:05',
text: 'New event',
id: '5c5a6bc5ea427e54cd4714d6',
'!nativeeditor_status': 'updated' }
The id you are seeing is the EVENT id. I want to add a field userID using passport (req.user.id) that way I can then search the collection and populate events of the logged in player.
My question is how to add fields to the req.body element? My calendar and player schemas are as follows:
player.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
calendar: {
type: Schema.Types.ObjectId, ref: 'calendar'
}
});
const User = mongoose.model('player', UserSchema);
module.exports = User;
calendar.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
text: {type: String, required: true},
start_date: {type: Date, required: true},
end_date: {type: Date, required: true},
user: {type: Schema.Types.ObjectId, ref: 'player', required: true}
});
const calendar = mongoose.model('calendar', schema);
module.exports = calendar;
Here is how I'm implementing the calendar in my route index.js:
//schedule
router.get('/calendar', ensureAuthenticated, function(req, res){
req.body.user = req.user.id;
var db = require('mongoskin').db("mongodb://tdipietro87:tdipietro87#tmcluster-shard-00-00-pbtwu.mongodb.net:27017,tmcluster-shard-00-01-pbtwu.mongodb.net:27017,tmcluster-shard-00-02-pbtwu.mongodb.net:27017/test?ssl=true&replicaSet=TMCluster-shard-0&authSource=admin&retryWrites=true", { w: 0});
db.bind('calendar');
var Calendar = require('../models/calendar');
Calendar.find({user: req.user.id}) // query by specific user
.then(function (data) {
// ...
router.use(express.static(path.join(__dirname, 'public')));
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
router.get('/init', function(req, res){
db.calendar.insert({
text:"My test event A",
start_date: new Date(2018,8,1),
end_date: new Date(2018,8,5)
});
db.calendar.insert({
text:"My test event B",
start_date: new Date(2018,8,19),
end_date: new Date(2018,8,24)
});
db.calendar.insert({
text:"Morning event",
start_date: new Date(2018,8,4,4,0),
end_date: new Date(2018,8,4,14,0)
});
db.calendar.insert({
text:"One more test event",
start_date: new Date(2018,8,3),
end_date: new Date(2018,8,8),
color: "#DD8616"
});
res.send("Test events were added to the database")
});
router.get('/data', function(req, res){
db.calendar.find().toArray(function(err, data){
//set id property for all records
console.log(err);
for (var i = 0; i < data.length; i++)
data[i].id = data[i]._id;
//output response
res.send(data);
});
});
router.post('/data', function(req, res){
console.log(req.body);
console.log(req.user.id);
var data = req.body;
var mode = data["!nativeeditor_status"];
var sid = data.id;
var tid = sid;
delete data.id;
delete data.gr_id;
delete data["!nativeeditor_status"];
function update_response(err, result){
if (err)
mode = "error";
else if (mode == "inserted")
tid = data._id;
res.setHeader("Content-Type","application/json");
res.send({action: mode, sid: sid, tid: tid});
}
if (mode == "updated")
db.calendar.updateById( sid, data, update_response);
else if (mode == "inserted")
db.calendar.insert(data, update_response);
else if (mode == "deleted")
db.calendar.removeById( sid, update_response);
else
res.send("Not supported operation");
});
res.render('calendar', {
name: req.user.name
})
});
});
This is very complicated to answer, but i want to give some clue
const newEvent = new Calendar({ //Calendar is your models name
....fill with another required field in models
text : req.body.text,
user : req.user.id //look again, how you decode incoming token request and declare them
});
I'm new to MongoDB/Mongoose and trying to figure out how to map relationships between Schema. I don't think issue is with .populate(). At creation of new user and clients, I do not see the relationship reflected in collection
User (login via local/social) has many Clients.
A set of Clients belong to 1 User
Is this the correct way to declare foreign key? {type: Schema.Types.ObjectId, ref: 'Client'}
Should both Schema have the each other's foreign key to relate to one another?
Is there any additional code required when creating User/Client in order for the data from foreign key to show up? I read something about populate()
User
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
local: {
id: String,
email: String,
password: String,
name: String,
mobile: String,
clients: {type: Schema.Types.ObjectId, ref: 'Client'}
},
google: {
id: String,
token: String,
email: String,
name: String,
clients: {type: Schema.Types.ObjectId, ref: 'Client'}
}
});
module.exports = mongoose.model('User', userSchema);
Client
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var clientSchema = new Schema({
id: String,
firstname: String,
lastname: String,
mobile: String,
user: {type: Schema.Types.ObjectId, ref: 'User'}
});
module.exports = mongoose.model('Client', clientSchema);
Create User
app.post("/api/user", function (req, res) {
const user = req.body;
console.log(user);
User.findOne({ 'local.email': user.email },
function (err, result) {
if (err) {
console.log(err);
handleError(err, res);
return;
}
if (result) {
res.status(500).send("Email already exists in database");
} else {
var newUser = new User();
newUser.local.password = generateHash(user.password);
newUser.local.email = user.email;
newUser.local.name = user.name;
newUser.local.mobile = user.mobile;
newUser.save(function (err, result) {
res.status(201).send("User added to database");
});
}
});
});
Create Client
app.post("/api/client", function (req, res) {
const client = req.body;
console.log(client);
Client.findOne({
$and: [
{ firstname: client.firstname },
{ lastname: client.lastname }
]
},
function (err, result) {
if (err) {
console.log(err);
handleError(err, res);
return;
}
if (result) {
res.status(500).send({msg:"Client already exists in database"});
} else {
var newClient = new Client();
newClient.firstname = client.firstname;
newClient.lastname = client.lastname;
newClient.mobile = client.mobile;
newClient.save(function (err, result) {
res.status(201).send("Client added to database");
});
}
});
});
So I am trying to hide the password object from showing. Here's my code, I am using bcrypt to ash the password. I am hiding the return objectBut I am not getting my expected results. What am I doing wrong, please help. Greatly appreciate it.
Thanks.
var express = require('express')
var router = express.Router()
var User = require('../Models/User.js')
var bcrypt = require('bcrypt')
router.get('/:resource', function(req, res, next){
var resource = req.params.resource
if (resource == 'user'){
User.find(null, function(err, users){
if(err) {
res.json({
confimration: 'error',
message: err
})
return
}
res.json({
confimration: 'success',
message: users
})
return
})
}
})
router.post('/:resource', function(req, res, next){
var resource = req.params.resource
var data = req.body
var password = data.password
var hashed = bcrypt.hashSync(password, 10)
data['password'] = hashed
if(resource == "user") {
User.create(data, function(err, user){
if(err){
res.json({
confirmation: 'fail',
message: err
})
return
}
res.json({
confirmation: 'success',
result: user
})
return
})
}
})
module.exports = router
var mongoose = require('mongoose')
var UserSchema = new mongoose.Schema({
firstName: {type: String, lowercase: true, trim: true, default: ''},
lastName: {type: String, lowercase: true, trim: true, default: ''},
email: {type: String, lowercase: true, trim: true, default: ''},
city: {type: String, default: ''},
password: {type: String, default: ''},
timestamp: {type:Date, default: Date.now}
})
UserSchema.methods.summary = function() {
var summary = {
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
timestamp: this.timestamp,
id: this._id,
city: this.city
}
return summary
}
module.exports = mongoose.model('UserSchema', UserSchema)
{
_id: "57f460235805b52762605df2",
__v: 0,
timestamp: "2016-10-05T02:06:27.829Z",
password: "$2a$10$DIHrMO8WcRmOkIVj93SSQ.LFe5vPYH6R3xrfsSuql.v2jfU2mcO.C",
city: "new york",
email: "4",
lastName: "4",
firstName: "4"
}
for the router.get you could use a projection field. I don't know why you have null. but this find searches for all the docs in users collection and excludes the password field for each doc returned. does this help with the router.get?
if (resource == 'user'){
User.find({},{password: 0}, function(err, users){
if(err) {
res.json({
confimration: 'error',
message: err
})
return
}
res.json({
confimration: 'success',
message: users
})
return
})
}
I am getting the correct data for friendRequests which is getting a user ID and throwing it in the friendRequest field of my mongoose file. When I add $push to add the data into the friendRequest array in the route file, it actually does not insert it and gives me back the err function I created.
Here is my route file:
exports.addContactPost = function(req, res, err) {
User.findByIdAndUpdate(req.signedCookies.userid, {
$push: {friendRequest: req.body.friendRequest}
}, function(err) {
if(err) {
console.log("post2");
return console.log('error');
}
else {
console.log('postsuccess');
res.json({response: true});
}
});
};
Here is the mongoose file:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt-nodejs'),
SALT_WORK_FACTOR = 10;
var UserSchema = new Schema({
email: { type: String, required: true, lowercase:true, index: { unique: true } },
password: { type: String, required: true },
firstName: {type: String, required: true},
lastName: {type: String, required: true},
phone: {type: Number, required: true},
birthday: {type: Date, required: true},
friendRequest: {type: Array},
friend: {type: Array}
});
UserSchema.pre('save', function(next) {
var user = this;
console.log("email exists");
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password along with our new salt
bcrypt.hash(user.password, salt, null, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('User', UserSchema);
So the document that mongo finds matching the provided userId does not have an array as its friendRequest property. Look at that specific document by ID in mongo shell and fix it so that friendRequest is an array.
I am unsure as to why I am getting an error for POST-ing a form. I am using mongoose to connect to mongodb and using Jade as my view engine. I am trying to POST an update and not a new account into the db, and using a cookie to pull the user's info. So it is the Edit User Profile page. Everything works on the Jade file and looks right, just when I hit the submit button it goes to a:
Cannot POST /editUserProfile
My mongoose User file:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt-nodejs'),
SALT_WORK_FACTOR = 10;
var UserSchema = new Schema({
email: { type: String, required: true, lowercase:true, index: { unique: true } },
password: { type: String, required: true },
firstName: {type: String, required: true},
lastName: {type: String, required: true},
phone: {type: Number, required: true},
birthday: {type: Date, required: true}
});
UserSchema.pre('save', function(next) {
var user = this;
console.log("email exists");
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password along with our new salt
bcrypt.hash(user.password, salt, null, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('User', UserSchema);
My route file:
exports.editUserProfile = function(req, res) {
User.findById(req.signedCookies.userid, function(err,user) {
if(err) {
res.send(err);
} else {
console.log(JSON.stringify(user));
res.render('editUserProfile', {title: 'Weblio',
ufirstName: user.firstName,
ulastName: user.lastName,
uemail: user.email,
uphone: user.phone,
ubirthday: user.birthday
});
//, user: user.firstName, - taken out after title
}
});
};
exports.editUserProfilePost = function(req, res) {
var updateUser = new User ({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
phone: req.body.phone,
birthday: new Date(req.body.birthday)
});
updateUser.save(function(err){
console.log("here 3");
if(!err) {
console.log("here3a");
res.render('userProfile', {title: 'Weblio'});
} else {
console.log("here 1a");
(new Error('Incorrect POST'));
return res.render('editUserProfileError', {title: 'Weblio'});
}
});
};
Jade file:
extends layout
block content
div.centerContent
form.validateForm(method="POST", action="/editUserProfile")
legend Edit Profile
input(type="text", name="firstName", maxlength="20", placeholder=ufirstName, value=ufirstName)
br
input(type="text", name="lastName", maxlength="20", placeholder=ulastName, value=ulastName)
br
input(type="email", name="email", maxlength="20", placeholder=uemail, value=uemail)
br
input(type="number", name="phone", maxlength="20", placeholder=uphone, value=uphone)
br
input(type="date", name="birthday", placeholder=ubirthday, value=ubirthday)
br
input.btn.btn-primary(type="submit", name="Update", value="Save")
a(href="/userProfile")
button.btn(type="button") Cancel
This is my app.js file: I have a bunch of other things in there but the Register part is getting POST-ed so I don't think the app.js has any problems.
app.get('/editUserProfile', user.editUserProfile);
app.post('/editUserProfile', user.editUserProfilePost);
Updated:
exports.editUserProfilePost = function(req, res, err) {
User.findByIdAndUpdate(req.signedCookies.userid,{
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
phone: req.body.phone,
birthday: new Date(req.body.birthday)
}, function(err) {
if(!err) {
console.log("post2");
res.render('userProfile', {title: 'Weblio'});
} else {
console.log("post3");
(new Error('Incorrect POST'));
return res.render('editUserProfileError', {title: 'Weblio'});
}
});
};