How do I check if a field already exists in the database? - mongodb

My problem is about checking if the name or email of a staff already exist in the database. They say its good to do it in the pre update middleware. I tried it but it's not working.
Im passing the (id_of_staff, updatedStaff_info and callback_function) to the update function.
Here's my update function:
module.exports.updateStaff = function(id, updatedStaff, callback){
var query = {_id: id};
Staff.update(query, updatedStaff, callback);
}
Everytime the Staff.update() is called the pre update middleware is executed. What I want here is check if the name or email if they already exist. The problem is, it seems that the name and email in the pre update middleware is undefined.
My pre update middleware:
staffSchema.pre("update", function(next){
var staff = this;
Staff.find({_id:{$ne: staff.id}, $or:[{name: staff.name}, {email: staff.email}]}, function (err, docs) {
if (!docs.length){
next();
}else{
next(new Error("Name or email already exist"));
}
});
});
The result that I got is always "Name or email already exist". And I tried to print in the console log the value of staff.name but it says its undefined. Am I doing it right? Can you help me to get it working. Thank you very much guys.

I found a solution to my question. Instead of using pre update middleware, I just create a function to check if the name or email already exist.
Here's the code:
module.exports.updateStaff = function(id, updatedStaff, callback){
var query = {_id: id};
//check name and email if already available
function updateStaff(id, updatedStaff, callback){
//get staff that has the same name or email
Staff.find({_id:{$ne:id}, $or:[{name: updatedStaff.name}, {email_pc: updatedStaff.email_pc}]}).exec(
function(err, result){
console.log(result);
if(!err){
if(result.length){
console.log("Name or email already exist.");
callback("Conflict", null);
}
else{
//udpate the staff
Staff.update(query, updatedStaff, callback);
}
}else{
callback(err);
}
})
}
updateStaff(id, updatedStaff, callback);
}
But I'm still open to answer using pre update middleware. Thanks :)

Related

Meteor check whether document already exists in collection or not?

I am beginner in meteor. I have a form having username and password as input fields and a submit button in the end.
I have correctly collected data from both fields into two variables. Now what I want is to verify whether any matching document exists in my MongoDB collection or not? My below code is not working. How to do it? Please help. Here is my code.
Template.form.events({
'submit.login':function(event){
event.preventDefault();
var user = document.getElementById("myForm").elements[0].value;;
var pass = document.getElementById("myForm").elements[1].value;
var usernamee = (Collection.Login.find({username: user},{password: pass})).count();
if(usernamee>0) {
alert("found");
} else {
alert("not found");
}
return false;
}
});
Firstly your .find() is incorrect:
var usernamee = (Collection.Login.find({username: user},{password: pass})).count();
shoud be:
var usernamee = (Collection.Login.find({username: user, password: pass})).count();
Assuming that you're publishing that collection to the client either with autopublish or an explicit publication.
However:
You are giving even non-logged in users access to the usernames and cleartext passwords of all other users!
Meteor includes the accounts package that takes care of user management for you. You don't need to reinvent the wheel. You want to take advantage of the security work that's already been done for you.
You can use a method call to find out if a username has already been used and warn the new user in the UI before they create their account.
client:
Meteor.call('usernameExists', username, function(err, result){
if (result) {
alert('Username '+username+' is already taken!')
// clear out the form etc...
}
});
server:
Meteor.methods({
usernameExists(username){
return Meteor.users.findOne({username}) !== 'undefined';
}
});

Can't find user by name with Monk / Mongo

I'm working on a CRUD application with Node, Mongo & Monk.
I'd like to find a record by username, and then update it.
But I'm unable to find a record, this code isn't working:
// GET User Profile
router.get('/userprofile', function(request,response){
var db = request.db;
var userName = request.body.username;
var collection = db.get('usercollection');
collection.findOne({
"username": userName
},{},function(e,user){
response.render('userprofile', {
"user": user
});
});
});
The "findOne" method doesn't return anything, and the "user" object ends up empty.
Remove the middle empty object from the signature for the findOne() method signature for the query to work:
Note: The way you are getting the userName is for when the request method is a POST, here you are doing a GET so you need to use the request.query property. More details here
var userName = request.query.username;
collection.findOne({"username": userName}, function(e,user){
response.render('userprofile', { "user": user });
});
If you want to update then you can use the update() method, suppose you want to update the username field to change it to 'foo', the following stub shows how you can do the update:
var u = collection.update({ "username": userName }, { "$set": { username: 'foo' } });
u.complete(function (err, result) {
console.log(err); // should be null
console.log(result); // logs the write result
});
Ok, I found out the problem.
Chridam's code was correct, but I also needed to change my form from a GET to a POST. Once I did that, the form POSTed and mongo could see request.body.username (it was null before) and look up my user using Chridam's code.
After reading Chridam's revised answer, was also able to get it to work with GET.
Now working on the update code..

How do I go about getting the current id of a local MongoDB I created?

Basically, I'm trying to compare the user's answer for a question in a "null" or local MongoDB to a key in another MongoDB that was declared before.
I know that to get the _id of the declared MongoDB (the real databse) is to call this._id, which is evident when I run console log on the browser console.
But how can I retrieve the _id of the local MongoDB?
Thanks in advance for any help.
Here is the helper code:
Template.question.events({
"click .button": function(e){
e.preventDefault;
for (var i = 0; i < document.getElementsByName("choices").length; i++){
if (document.getElementsByName("choices")[i].checked){
var init = document.getElementsByName("choices")[i].value;
}
}
Answers.insert({answer: init});
if(Answers.find({answer: init}) === Quiz.find({_id: this._id}, {answer: init})){
console.log("The answers match.");
}
}
});
The last part of the code is me attempting to compare the answer field in the "Answers" DB, which is the local DB to the answers field in the Quiz DB, which is the declared, legitimate database.
Edit:
So I used user "gdataDan" suggestion and changed my code to include a function taking in the error and result parameters + I added an else statement to see if the event helper actually is functioning properly until the end:
Template.question.helpers({
title: function(){
return Quiz.find();
}
})
Template.question.events({
"click .button": function(e){
e.preventDefault;
for (var i = 0; i < document.getElementsByName("choices").length; i++){
if (document.getElementsByName("choices")[i].checked){
var init = document.getElementsByName("choices")[i].value;
}
}
var id = "";
Answers.insert({answer: init}, function(error, result){
if (error){
console.log("error: " + error);
} else if (result){
id = result;
}
})
if(Answers.find({_id: id}, {answer: init}) === Quiz.find({_id: this._id}, {answer: init})){
console.log("The answers match.");
} else {
console.log("Something went wrong.");
}
}
});
Turns out that console log prints "Something went wrong," even though the answers match between both databases. So I feel like the way I call the find function or the id's themselves don't match.
Edit#2:
I tried declaring the init variable outside the loop and tried using the $eq operator for MongoDB and still get the "Something went wrong" message in the console.
collection.insert will return the ID if there is no error.
var id = ''
Answers.insert({answer: init},function(error,result){
if(error) console.log('error: ' + error);
if(result) id = result;
});

Mongoose findByIdAndUpdate not working

I have a fairly straight forward method below to update a document based on its ObjectId. It does not return an error but it fails to make the required updates to the document. I think it is failing because, according to my research, findByIdAndUpdate() takes only plain Javascript whereas job._id is an ObjectId from the document that I want to update. Can someone tell me how to make this work correctly?
function handleEncoderResponse(xmlResponse, job) {
var r = et.parse(xmlResponse);
var mediaID = r.findtext('./MediaID');
var message = r.findtext('./message');
EncodingJob = mongoose.model('EncodingJob');
EncodingJob.findByIdAndUpdate( job._id, {
"MediaID": mediaID,
"Status": message
}, function(err, result) {
if (err) console.log(err);
console.log(result);
});
}
Edit: Per this question Mongoose update document Fail with findByIdAndUpdate
I also tried the following code to no avail.
job.MediaID = mediaID;
job.Status = message;
job.save(function(err, res) {
if(err) console.log(err);
});
This approach yields the issue. It does not update the document and it does not return an error.
As it turns out, my mistake was forgetting to define MediaID and Status in the Schema as follows:
var encodingJobSchema = new mongoose.Schema({
...
MediaID: String,
Status: String
});

how to check whether username and password exists inside database(mongodb)

i want to store username and password inside mongodb database and later on retrieve database values and check whether the username and password exists inside database.If it does exist then i would redirect to another page.How can i achieve this using node.js and mongodb.I am able to store the values inside database.But getting confused for how to fetch the values and check them against the values provide in form field values.There is no method in mongodb like fetchByName or something similar.
Can someone help me out with the code.
I think you should take a look on the Nodepad source code, it explains very well how to achieve this with Mongoose:
User.virtual('password')
.set(function(password) {
this._password = password;
this.salt = this.makeSalt();
this.hashed_password = this.encryptPassword(password);
})
.get(function() { return this._password; });
User.method('authenticate', function(plainText) {
return this.encryptPassword(plainText) === this.hashed_password;
});
User.method('makeSalt', function() {
return Math.round((new Date().valueOf() * Math.random())) + '';
});
User.method('encryptPassword', function(password) {
return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
});
User.pre('save', function(next) {
if (!validatePresenceOf(this.password)) {
next(new Error('Invalid password'));
} else {
next();
}
});
try using an already existing library like passport or everyauth. There are other ones too, google them :)