How do I save to mongodb using mongoos and express? - mongodb

I can't save a user to my mongodb, but I can get document. I get the following error each time I try to save a user. I get error from line 27 that's where the email starts from. I have tried other means too but the truth is that I am new to mongodb so I can't tell if the error is from the
code or from the mongodb server. Please help.
error: falior when reseiving data from peer
let User = require('../models/user.model')
const userController = {
//get all the users from the database
getall :(req, res) =>
{
User.find()
.then((users)=>res.json(users))
.catch(err => res.status(400)
.json('Error: ' + err));
/*{field: filter},*/
},
//register users //
register :(req, res) =>{
const {body} = req
const {
firstname,
lastname,
email,
mobile,
password
} = body;
//this is where the error start reporting for
email = email.toLowerCase()
User.find({ email : email}, (err, previousUser) => {
if(err){
res.end({ success : false, message : `Error ${err}`})
}
else
{
if(previousUser.length > 0){
res.end({ success : false, message : 'Already registerd empty'
})
}
else
{
//using user model
const newUser = new User();
//asign values to the user model
newUser.firstname = firstname
newUser.lastname = lastname
newUser.mobile = mobile
newUser.email = email
newUser.password = newUser.generateHash(password)
//save
newUser.save()
.then(()=>res.json('you have succesfuly registerd'))
.catch(err => res.status(400).json('Error: ' + err));
}
}
});
}
}
module.exports = userController

I was so dumb the react component for the code above was not passing the required data for the Fields

Related

How to get other member discord id?

i want to make command that can give me information about someone that i mention like !info #Someone i try code below, but didnt work.
This is the schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const profileSchema = new Schema({
_id: mongoose.Schema.Types.ObjectId,
userID: String,
nickname: String,
ar: Number,
server: String,
uid: Number,
});
module.exports = mongoose.model("User", profileSchema);
and this is what i try, but show nothing, didnt show any error sign.
client.on("message", async msg => {
let member = msg.mentions.users.first().username
if (msg.content === `!info #${member}`){
userData = await User.findOne({userID : msg.mentions.users.first().id});
if (userData) {
const exampleEmbed = new MessageEmbed()
.setColor('#808080')
.setTitle('Data Member')
.setDescription(`**Nickname :** ${userData.nickname}\n**Adventure Rank :** ${userData.ar}\nServer: ${userData.server}\n**User ID :** ${userData.uid}`)
.setThumbnail(msg.author.avatarURL())
msg.reply({ embeds: [exampleEmbed] });
} else{
msg.reply("Please registration first")
}
}
}
);
By seeing your code, it might shuffle all of your .first() lets modify your code.
client.on("message", async msg => {
let member = msg.mentions.members.first() || msg.guild.members.fetch(args[0]); //You can also use their ID by using these
if (msg.content === `!info ${member.username || member.user.username}`) { //then adding the user.username
const userData = await User.findOne({
userID: member.id || member.user.id //same as here
}); //userData shows as "any" so you need to change it to const userData
if (userData) {
const exampleEmbed = new MessageEmbed()
.setColor('#808080')
.setTitle('Data Member')
.setDescription(`**Nickname :** ${userData.nickname}\n**Adventure Rank :** ${userData.ar}\nServer: ${userData.server}\n**User ID :** ${userData.uid}`)
.setThumbnail(msg.author.avatarURL())
msg.reply({
embeds: [exampleEmbed]
});
} else {
msg.reply("Please registration first")
}
}
});
Change the if condition. How Discord Mentions Work
Discord uses a special syntax to embed mentions in a message. For user mentions, it is the user's ID with <# at the start and > at the end, like this: <#86890631690977280>.
if (msg.content === `!info ${message.mentions.users.first()}`)
For example:
const member = msg.mentions.users.first();
if (msg.content === `!info ${member}`){
User.findOne({ userID: member.id }, (err, user) => {
if (err) return console.error(err);
if (!user) return msg.reply("User not found");
console.log(user);
});
}
Going through your code, I found these errors.
first of all you need members not users in message.mentions.members.first().
Second of all, you need to define UserData first like const UserData = ...
client.on("message", async msg => {
let member = msg.mentions.members.first()
if (msg.content === `!info #${member}`){
User.findOne({userID : member.id}, async (err, userData) => {
if (userData) {
const exampleEmbed = new MessageEmbed()
.setColor('#808080')
.setTitle('Data Member')
.setDescription(`**Nickname :** ${userData.nickname}\n**Adventure Rank :** ${userData.ar}\nServer: ${userData.server}\n**User ID :** ${userData.uid}`)
.setThumbnail(msg.author.avatarURL())
msg.reply({ embeds: [exampleEmbed] });
} else{
msg.reply("Please registration first")
}
}
});
});
Let me know if it works after fixing these errors.
Also message event is depricated so try using MessageCreate instead from now on

Error: TypeError: user.insertOne is not a function using mongoose

I'm having difficulty creating the routes to send to MongoDB.
When I return user, it returns the full database. This goes for using User or 'user'.
User is a model
let User = require('../models/user.model');
User.findById(req.params.id)
.then(user => {
if (!user)
res.status(404).send("data is not found");
else
for(var key in req.body.proposal) {
//res.send(user.proposal)
//res.send(user)
//res.send(User.username)
user.proposal.insertOne(
{
"uid" : req.body.proposal[key].uid,
"clientEmail" : req.body.proposal[key].clientEmail,
"summary" :req.body.proposal[key].summary,
"terms" :req.body.proposal[key].terms,
"form" :req.body.proposal[key].form
} //update
)
}
user.save()
.then(user => res.json(user))
.catch(err => res.status(400).json('Error: ' + err));
})
.catch(err => res.status(400).json('Error: ' + err));
});
Thank you in advanced!
It should be something like this :
let proposalArr = [];
for (const key in req.body.proposal) {
proposalArr.push({
uid: req.body.proposal[key].uid,
clientEmail: req.body.proposal[key].clientEmail,
summary: req.body.proposal[key].summary,
terms: req.body.proposal[key].terms,
form: req.body.proposal[key].form
});
}
user.proposal = proposalArr;
user.save().............
You can't use .insertOne on result of database query, it's a function of mongoose model to insert new document to collection but not to insert new fields to objects. You need to do just like adding new fields to json object using .js code, but mongoose will keep track of object's changes & when you use .save() it can update the document in collection with all those changes.
Instead of two DB calls, you can do that in one call, Check : .findByIdAndUpdate() & try below sample code :
let proposalArr = [];
for (const key in req.body.proposal) {
proposalArr.push({
uid: req.body.proposal[key].uid,
clientEmail: req.body.proposal[key].clientEmail,
summary: req.body.proposal[key].summary,
terms: req.body.proposal[key].terms,
form: req.body.proposal[key].form
});
}
User.findByIdAndUpdate(
req.params.id,
{
proposal: proposalArr
},
{ new: true }
)
.then(user => {
if (!user) res.status(404).send("data is not found");
res.json(user);
})
.catch(err => res.status(400).json("Error: " + err));

JWT - Retrieving Token

I am trying to figure out how do I get the token id or a new token for an existing user using JWT. The goal is to take email and password, find it in the mongo DB, and then send back to the client the token, then store the token for the session.
Currently when registering I encrypt the password and store the email, name, and password in a mongoDB.
Based on what I have been learning, the actual token is not stored in the mongoDB, but the token is generated from the _id, which I cant pull for some reason to just resign and get the token back but no luck. Any advice is greatly appreciated its for a personal project.
User.create({
name : req.body.name,
email : req.body.email,
password : req.body.password,
},
function (err, user) {
if (err) return res.status(500).send("There was a problem registering the user.")
// create a token
var token = jwt.sign({ id: user._id }, config.secret);
res.status(200).send({ auth: true, token: token });
});
You can try user._id.toString() or user.id instead of user._id to retrieve the user id.
You may get some idea from the code below how you can use JWT token for verification purpose.
login: (req, res) => {
const { name, password } = req.body;
mongoose.connect(connUri, { useNewUrlParser: true }, (err) => {
let result = {};
let status = 200;
if(!err) {
User.findOne({name}, (err, user) => {
if (!err && user) {
// We could compare passwords in our model instead of below as well
bcrypt.compare(password, user.password).then(match => {
if (match) {
status = 200;
// Create a token
const payload = { user: user.name };
const options = { expiresIn: '2d', issuer: 'anshukumar.me' };
const secret = process.env.JWT_SECRET;
const token = jwt.sign(payload, secret, options);
// console.log('TOKEN', token);
result.token = token;
result.status = status;
result.result = user;
} else {
status = 401;
result.status = status;
result.error = `Authentication error`;
}
res.status(status).send(result);
}).catch(err => {
status = 500;
result.status = status;
result.error = err;
res.status(status).send(result);
});
} else {
status = 404;
result.status = status;
result.error = err;
res.status(status).send(result);
}
});
} else {
status = 500;
result.status = status;
result.error = err;
res.status(status).send(result);
}
});
}
You can also check this GitHub repo which has implemented JWT Token in Node JS.
https://github.com/kumaranshu72/JWT-nodeJS
You may also follow the following tutorial to get a good idea of how to implement JWT authentication : https://scotch.io/tutorials/authenticate-a-node-es6-api-with-json-web-tokens
I think you can access the id without _
User.create({
name : req.body.name,
email : req.body.email,
password : req.body.password,
},
function (err, user) {
if (err) return res.status(500).send("There was a problem registering the user.")
// create a token
var token = jwt.sign({ id: user.id }, config.secret);
res.status(200).send({ auth: true, token: token });
});
user.id instead of user._id

Mongoose cannot findOne({_id : id}) with copied documents

I copied documents from a local database to my production database and when I try to get the document by Id by running model.findOne({_id : id}) and mongoose returns nothing. I am copying the documents over with the same Id, but I also tried with a new Id. I can find the document in the database and confirm that the JSON is correct, the Id is correct, etc and it won't find it. The documents I did not copy and where generated via my app still query fine with the findOne command. So, I have no idea what's going on
any help is greatly appreciated, thanks
groups.crud
getGroupById(id: string) {
logger.debug(".getGroupById id: " + id);
return new Promise(function(resolve, reject) {
GroupsModel.findById(id)
.populate('createdBy')
.then(function (group) {
logger.debug(".getGroupById");
if(group.createdBy.privacySettings.useUserName) {
group.createdBy.firstName = '';
group.createdBy.lastName = '';
}
resolve(group);
})
.catch(function(error) {
reject(error);
});
});
}
groups.routes
getGroupById(req, res, next) {
logger.debug('.getGroupById: BEG');
let id = req.params.id;
return groupsCrud.getGroupById(id)
.then(function(group) {
if(group) {
logger.debug('.getGroupById: get by id success');
let response = {
data : group
}
logger.debug('.getGroupById: response: ' + response);
res.json(response);
}
else {
logger.debug('.getGroupById: get by id failed 1');
res.status(404).json({ status : 404, message : "Group not found."});
}
})
.catch(function(error) {
logger.debug('.getGroupById: get by id failed 2 err = ' + JSON.stringify(error, null, 2));
res.sendStatus(404);
});
}

How can I call req.flash() from inside the mongoose save function?

Upon finding duplicate user entries in my database, I want to flash a message to the view using req.flash(). However, the only parameters allowed in the User.save() function are errors and the results of the save. How can I get the request object in there too so that if there is
an error (i.e. duplicate entry), the user is notified?
requires
const express = require('express')
const router = express.Router()
const mongoose = require('mongoose')
const Quote = require('../models/quotes')
const User = require('../models/users')
const ObjectId = mongoose.Types.ObjectId;
const expressValidator = require('express-validator')
const flash = require('express-flash-messages')
const passport = require('passport')
const bcrypt = require('bcrypt')
const saltRounds = 10
get request:
/* route handling for SIGNUP page. */
router.get('/signup', (req, res, next) => {
const flashMessages = res.locals.getMessages()
console.log('flash:', flashMessages)
if (flashMessages.error) {
console.log('flash:', flashMessages)
res.render('signup', {
showErrors: true,
signupErrors: flashMessages.error
})
} else {
console.log('no flash errors detected.')
res.render('signup')
}
})
post request:
/* route handling for submission to SIGNUP page */
// this is all just front end validation, with no relation to the database. I think flash messages use that
router.post('/signup/users', (req, res, next) => {
req.checkBody('username', 'Username field cannot be empty.').notEmpty()
req.checkBody('username', 'Username must be between 4-30 characters long.').len(4, 30)
req.checkBody('email', 'The email you entered is invalid, please try again.').isEmail()
req.checkBody('email', 'Email address must be between 4-100 characters long, please try again.').len(4, 100)
req.checkBody('password', 'Password must be between 8-100 characters long.').len(8, 100)
// req.checkBody('password', 'Password must include one lowercase character, one uppercase character, a number, and a special character.').matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.* )(?=.*[^a-zA-Z0-9]).{8,}$/, 'i')
req.checkBody('passwordMatch', 'Password must be between 8-100 characters long.').len(8, 100)
req.checkBody('passwordMatch', 'Passwords do not match, please try again.').equals(req.body.password)
// Additional validation to ensure username is alphanumeric with underscores and dashes
req.checkBody('username', 'Username can only contain letters, numbers, or underscores.').matches(/^[A-Za-z0-9_-]+$/, 'i')
const errors = req.validationErrors()
if(errors || flashMessages.error) {
res.render('signup', {
errors: errors,
showErrors: true,
signupErrors: flashMessages.error
})
} else {
let password = req.body.password
bcrypt.hash(password, saltRounds, (err, hash) => {
user = new User()
user.username = req.body.username
user.email = req.body.email
user.password = hash
// PROBLEM STARTS HERE
user.save((err, result) => {
if(err) {
// add flash message here to let user know something was wrong!
const flashMessages = res.locals.getMessages()
console.log('flash', flashMessages)
console.log("Your error: ", err.message)
if (err.message.indexOf("duplicate key error") > -1) {
req.flash('signupErrors', "Username already in use.")
console.log(req.flash("hi"))
res.redirect('/signup')
console.log("Made it down here.")
} else {
req.flash('signupErrors', "There was a problem with your registration.")
console.log("Made it wayyyyyy down here.")
res.redirect('/signup')
}
// AND ENDS HERE
} else {
User.find({}).sort({ _id:-1 }).limit(1)
.exec((err, newuser) => {
if (err) {
console.log(err)
} else {
// logins user through passport function
req.login(newuser[0], (err) => {
if (err) {
console.log("Login error 1: " + err)
console.log("Login error 2: " + newuser[0])
console.log("Login error 3: " + newuser[0]._id)
} else {
console.log("Login sucess BULK: " + newuser[0])
console.log("Login success ._id: " + newuser[0]._id)
res.redirect('/home')
}
})
}
})
.catch(next)
}
})
})
}
})
/* route handling for submission to LOGIN page */
router.post('/login/users', passport.authenticate('local', {
successRedirect: '/profile',
failureRedirect: '/login',
failureFlash: true
}))