i am trying to add some data inside my MongoDB database, but i am not able to remove duplicate entries.
please help me to do so.
i am using node js and mongoose.
app.post('/', function (req, res) {
const newUser = new Newsletter ({
fname: req.body.fname,
lname: req.body.lname,
message: req.body.message,
email: req.body.email
});
newUser.save(function (err) {
if (!err) {
res.render("success");
} else {
const errCode = res.statusCode;
res.render("failure", { errStatusCode: errCode });
}
})
})
Related
I am trying to get the candidate or HR (user roles) object using mongoose and nodejs. I have a user and both roles are derived from it.
when trying to connect using a UNIQUE username and a password. A user object will be sent as a result. I want to also send candidate/ or HR that are linked to that user.
I am passing the user object by reference to the candidate/HR schema:
const candidateSchema = new Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
index: true,
},
fullName: String,
profilePhoto: String,
birthday: Date,
I need to get the candidate object of the user that i get inside the exec() function. save it in a variable and send it as a res to signin function
app.post("/api/auth/signin", (req, res) => {
User.findOne({
username: req.body.username,
})
.populate("roles", "-__v")
.exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
const candi = candidat.findOne({ user: user }).exec((err, candidate) => {
//I want to save the candidate var
}));
//console.log("res",candi);
.....
});
A simple solution will be to wrap your code inside a promise and resolve whatever you want to store to variable while reject when you want to send error.
But its recommended to break down your code to multiple async functions and await them instead of using callback exec functions.
app.post("/api/auth/signin", async (req, res) => {
try{
let response = await new Promise((resolve,reject)=>{
User.findOne({
username: req.body.username,
})
.populate("roles", "-__v")
.exec((err, user) => {
if (err) {
//REJECT ERROR
reject(err);
return;
}
const candi = candidat.findOne({ user: user }).exec((err, candidate) => {
//RESOLVE YOUR CANDIDATE
resolve(canditate);
}));
//console.log("res",candi);
.....
});
.... your rest of code
})
res.send(response) // or required json
}catch(err){
res.status(500).send({ message: err });
}
}
I am very new to the MERN stack and I would like some help figuring out this error. I'm trying to check if an email is already in the database upon creating a new user. Can anyone tell me why I am getting this error?
The model and scheme
//schema
const Schema = mongoose.Schema;
const VerificationSchema = new Schema({
FullName: String,
email: String,
password: String,
date: Date,
isVerified: Boolean,
});
// Model
const User = mongoose.model("Users", VerificationSchema);
module.exports = User;
The Api
const express = require("express");
const router = express.Router();
const User = require("../Models/User");
router.get("/VerifyEmail", (req, res) => {
console.log("Body:", req.body);
const data = req.body;
const newUser = new User();
newUser.find({ email: data.email }, function (err, newUser) {
if (err) console.log(err);
if (newUser) {
console.log("ErrorMessage: This email already exists");
} else {
console.log("This email is valid");
}
});
res.json({
msg: "We received your data!!!",
});
});
module.exports = router;
The api caller using axios
const isEmailValid = (value) => {
const info = {
email: value,
};
axios({
url: "http://localhost:3001/api/VerifyEmail",
method: "get",
data: info,
})
.then(() => {
console.log("Data has been sent");
console.log(info);
})
.catch(() => {
console.log("Internal server error");
});
};
if you have body in your request, change the type of request to POST...
after that for use find don't need to create a instance of model, use find with Model
router.get("/VerifyEmail", (req, res) => {
console.log("Body:", req.body);
const data = req.body;
User.find({ email: data.email }, function (err, newUser) {
if (err) console.log(err);
if (newUser) {
console.log("ErrorMessage: This email already exists");
} else {
console.log("This email is valid");
}
});
res.json({
msg: "We received your data!!!",
});
});
I prefer to use async/await and don't use Uppercase world for routing check the article: like this
router.post("/verify-email", async (req, res) => {
try {
let { email } = req.body;
let newUser = await User.findOne({ email });
if (newUser) {
console.log("ErrorMessage: This email already exists");
} else {
console.log("This email is valid");
}
} catch (error) {
res.json({
msg: "somthing went wrong",
});
}
res.json({
msg: "We received your data!!!",
});
});
The proper way to query a Model is like so:
const User = mongoose.model('Users');
User.find({<query>}, function (err, newUser) {...
So you need to get the model into a variable (in this case User) and then run the find function directly against it, as opposed to running it against an object you instantiate from it. So this is incorrect:
const newUser = new User();
newUser.find(...
So assuming all your files and modules are linked up correctly, this should work:
const User = require("../Models/User");
User.find({<query>}, function (err, newUser) {...
The problem wasn't actually the mongoose function but I needed to parse the object being sent.
let { email } = JSON.parse(req.body);
Before parsing the object looked like {"email" : "something#gmail.com"}
and after parsing the object looked like {email: 'something#gmail.com'}
I also changed the request from 'get' to 'post' and instead of creating a new instance of the model I simply used User.find() instead of newUser.find()
I'm working as API Backend with NodeJS. In case, when I insert 1 row the data will automatically updated to DB and Goolge Sheet API.
I already create the code in controller but I want to make it as Async Await, to makesure data inserted to DB first.
Here is my code:
createUser: (req, res, next) => {
bcrypt.genSalt(Number(env.SALTROUNDS_USER), (err, resultSalt) => {
bcrypt.hash(req.body.password, resultSalt, (err, hash) => {
doc.useServiceAccountAuth(creds, function(err){
// regis to db
let datauser = new modelsUsers({
email: req.body.email,
name: req.body.name,
password: hash,
phone_number: req.body.phone_number
});
//regis to GoogleSheetApi
doc.addRow(1,{
timestamps: tgl_ob,
name: req.body.name,
email: req.body.email,
phone_number: req.body.phone_number
},function(err){
if(err){
console.log(err); //errors
}
});
if(err){
console.log(err); //success
}
datauser.save((err, result) => {
if (result) res.send(result);
else res.send(err);
});
})
});
});
},
You can use util to make callbacks to promise
const GoogleSpreadsheet = require('google-spreadsheet');
const { promisify } = require('util')
const doc = new GoogleSpreadsheet(process.env.sheetid);
const creds = require('./../creds.json') // JSON file you can get from serviceaccount
createUser: (req, res, next) => {
bcrypt.genSalt(Number(env.SALTROUNDS_USER), (err, resultSalt) => {
bcrypt.hash(req.body.password, resultSalt, async (err, hash) => {
// you can also convert genSalt, salt to Promis
await promisify(doc.useServiceAccountAuth)(creds)
const info = await promisify(doc.getInfo)();
const sheets = info.worksheets;
let datauser = new modelsUsers({
email: req.body.email,
name: req.body.name,
password: hash,
phone_number: req.body.phone_number
});
const data = {
timestamps: tgl_ob,
name: req.body.name,
email: req.body.email,
phone_number: req.body.phone_number
}
// as you need to save to DB first and then add ROW to sheet
datauser.save(async (err, result) => {
if (result) {
await addRows(sheets, 1, data) // you can wrap in try catch for error handling
res.send(result);
}
else res.send(err);
});
})
});
}
function addRows(sheet, index, data) {
return new Promise((resolve, reject) => {
sheet[index].addRow(data, (err, row) => {
if (err) return reject(err)
resolve(row)
})
})
}
I'm using Node.js with Mongoose and Passport trying to get the user to save to the DB but keep encountering the error where No Username was given. I can get it to save if just using using username and password but as soon as I try to add more fields I get the issue. This is the code I have:
app.js
const userSchema = new mongoose.Schema ({
firstname: String,
lastname: String,
username: String,
password: String,
userLevel: {type: Number},
profileImage: String,
title: String
});
//ENABLE PASSPORT LOCAL
userSchema.plugin(passportLocalMongoose, {
selectFields: ' firstname lastname username password userLevel profileImage title'
});
//CREATE NEW model
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.get('/control', (res, req) => {
if (req.isAuthenticated()) {
res.render('control');
} else {
res.redirect('/login')
}
});
app.post("/register", (req, res) => {
User.register(new User(
{firstname: req.body.firstname},
{lastname: req.body.lastname},
{username:req.body.username},
{userLevel: 1},
{profileImage:"not set"},
{title:"not set"}
),
req.body.password,
(err, user) => {
if (err) {
console.log(err);
console.log(req.body.username);
} else {
passport.authenticate('local')(req, res, () =>{
res.redirect('/control');
});
}
});
});
Figured it out! I was using individual objects rather that just the one object :
User.register((
{firstname: req.body.firstname,
lastname: req.body.lastname,
username: req.body.username,
userLevel: 1,
profileImage:"not set",
title:"not set"
}),
req.body.password,
(err, user) => {
if (err) {
console.log(err);
console.log(req.body.username);
} else {
passport.authenticate('local')(req, res, () =>{
res.redirect('/control');
});
}
});
});
I am developing application with nodejs and express. I have login page. I am posting user data and if there is no user with that data then i want to redirect page. But res.render not working(I added comment where res.render is in my code like "//Redirect if user not found". Have no idea. Here is my code:
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/fuatblog");
var UserSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
age: Number
}),
Users = mongoose.model('Users', UserSchema);
app.post('/sessions', function (req, res) {
console.log(req.body.user.email);
console.log(req.body.user.password);
Users.find({
email: req.body.user.email,
password: req.body.user.password
}, function (err, docs) {
if (! docs.length) {
// no results...
console.log('User Not Found');
//res.status(400);
//Redirect if user not found
return res.render(__dirname + "/views/login", {
title: 'Giriş',
stylesheet: 'login',
error: 'Email or password is wrong.'
});
}
console.log('User found');
req.session.email = docs[0].email;
console.log(req.session.email);
});
return res.redirect('/Management/Index');
});
The .render method which you want to be invoke when the user is not recognized is in async code. This means that the return res.redirect('/Management/Index'); is called once the request reaches your server. But you should do that once you get the result from Users.find. I.e.:
app.post('/sessions', function (req, res) {
console.log(req.body.user.email);
console.log(req.body.user.password);
Users.find({
email: req.body.user.email,
password: req.body.user.password
}, function (err, docs) {
if (! docs.length) {
// no results...
console.log('User Not Found');
//res.status(400);
//Redirect if user not found
return res.render(__dirname + "/views/login", {
title: 'Giriş',
stylesheet: 'login',
error: 'Email or password is wrong.'
});
}
console.log('User found');
req.session.email = docs[0].email;
console.log(req.session.email);
return res.redirect('/Management/Index');
});
});