How can I use Node.js to get some specific value?

Hi there,

For example, suppose there are data like the following, the user’s name is “John Smith” and There are Email and encrypted password.

I have an input form in HTML where the user enters their Email and password, and the password is encrypted and checked to make sure it matches the password in the database.

I know how to make sure an Email exists.

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const crypto = require("crypto");

app.use(bodyParser.urlencoded({extended: true}));

mongoose.connect("/*.....*/");


const usersSchema = {
	email: String,
	password: String
}

const User = mongoose.model("User", usersSchema);

app.get("/", function(req, res) {
	res.sendFile(__dirname + "/example_form.html");
})

app.post("/", function(req, res) {
	User.findOne({ email: req.body.email}).then(user => {
      	if (user) {
      		//after process
      	} else {
      		res.send("Your email is invalid.");
		}
	})	
})

And I also know how to make sure the Password and Email match.

app.post("/", function(req, res) {
	User.findOne({ email: req.body.email}).then(user => {
      	if (user) {
      		/*
      			encryption process
			*/

			var crypted = cipher.update(userStr, 'utf8', 'hex');
			crypted += cipher.final('hex');
			const constid = req.body.email;

			User.findOne({ email: req.body.email, password: crypted}).then(user => {
				if(user) {
					res.send("Success.");
				} else {
		      		res.send("Email or password is wrong.");
				}
			})
      	} else {
      		res.send("Your email is invalid.");
		}
	})	
})

btw for this situation, how can I get a name value like “John Smith” by entered Email and Password value?

Hi @YumaSan and welcome to the MongoDB community forum!!

To find the name for a valid email id and password, you could directly use email to find the user and project only the username.

const filter = {
  'email': req.body.email
};
const projection = {
  '_id': 0, 'name': 1
};

const cursor = coll.find(filter, { projection });
const name = await cursor.toArray();

This would give an output of the username which matches with the correct email id and the password.

However I would have to mention that storing encrypted password is inherently insecure. If the primary need for this code is for authentication, I would recommend you to check out passport.js or similar.

Let us know if you have any further questions.

Best Regards
Aasawari