how to check whether username and password exists inside database(mongodb) - 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 :)

Related

text index required for $text query in the MongoDB with Express

I built a Express back-end which is connected to local MongoDB
when I create a post to find out the specific term, it returns the error like this
MongoError: text index required for $text query
How can I fix this error?
this is my Express code
app.post("/api/search",(req,res)=> {
const term = req.body.searchTerm;
console.log(term); // Here I can check the request coming well
MongoClient.connect(url,(err,db)=> {
if(err) throw err;
const dbo = db.db("Exercise");
dbo.collection("exercise")
.find({$text:{$search:term}})
.toArray((error, result) => {
if (error) {
console.log(error);
return;
} else {
console.log("Success");
res.send(result);
}
});
});
});
Thank you in advance!
What you can do to solve your problem is simple. You can create a "text" on the field that you want search in you collection like this:
db.reviews.createIndex( { comments: "text" } )
Note: assumes "comments" is the field as seen in the docs
However, for the best results you might want to create a dynamic default Search index in MongoDB Atlas. It's free and easy. Because it is a dynamic default, you do not need to do any configuration. The results and performance will likely be better if you are powering a search experience.
I hope this info helps.

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';
}
});

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

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 :)

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 to find a document from mongodb using mongoose based on query and then insert some data to it and save back?

I have my Model as
var Model = {"name":String,"email":String,"notes":[{"time":Date,"title":String,"description":String}]
And I want to find document based on the email, and then add a note to the array. And then save it back.
What I tried is,
var updatedNote = {};
Model.findOne({'email':'test#test.com'},function(err, note){
for(var property in note._doc){
if(note._doc.hasOwnProperty(property)){
updatedNote[property] = note._doc[property];
};
}
updatedNote.notes.push(newNote);
note._doc = updatedNote;
note.save(function(err){
if(err){
console.log(error);
}
else {
res.redirect('/notes');
}
})
});
But it is throwing error as "Object does not have save method". I don't want to use findByIdAndUpdate() as i am leaving this responsibility of generating id on mongo.
I don't understand what most of that code is doing. If I wanted to add a note to the document (I'm assuming newNote is defined elsewhere), I'd just do:
Model.findOne({'email':'test#test.com'},function(err, note){
note.notes.push(newNote);
note.save(function(err){});
});