I´m getting a problem with Mongoose Nodejs
This is my code for Controllers to Insert user in the database using Schema User from imported another file.
router.post('/insert', function insertUsert(req, res){
var newUser = User({
name: req.body.name,
username: req.body.username,
password: req.body.password,
admin: false
});
newUser.save(function(err){
if(err){
res.status(400).send(err);
}else{
res.status(201).send("User Inserted)");
}
})
});
This is my connection Mongoose:
var dbURI = 'mongodb://localhost/trabbel';
if (process.env.NODE_ENV === 'production') {
dbURI = process.env.MONGOLAB_URI || 'mongodb://<>:<>#ds133465.mlab.com:33465/locations';
mongoose.connect(dbURI);
console.log(dbURI);
}
// CONNECTION EVENTS
mongoose.connection.on('connected', function() {
console.log('Mongoose connected to ' + dbURI);
});
When I execute with Postman in the Route:
POST /user/insert - - ms - -
The .connect is inside a condition that runs only on production, turn it to:
if (process.env.NODE_ENV === 'production') {
dbURI = process.env.MONGOLAB_URI || 'mongodb://<>:<>#ds133465.mlab.com:33465/locations';
}
mongoose.connect(dbURI);
console.log(dbURI);
try it
That pass a reference of function in router.post
router.post('/insert', insertUsert);
function insertUsert(req, res, next){
const newUser = new User({
name: req.body.name,
username: req.body.username,
password: req.body.password,
admin: false
})
newUser.save().then(function(user) {
if(err) res.status(400).json({"message": err})
res.status(200).json(user)
})
}
Try using the below code. while inserting, you need to use new keyword
router.post('/insert', function insertUsert(req, res, next){
new User({
name: req.body.name,
username: req.body.username,
password: req.body.password,
admin: false
}).save(function(err, user){
if(err){
return next(err);
}
res.status(201).send("User Inserted)");
})
});
I think this adjustment to your code will make it work. I figured out you forgot the new keyword in creating the instance of your user model. I believe that will fix your problem.
router.post('/insert', function insertUsert(req, res, next){
var newUser = new User({
name: req.body.name,
username: req.body.username,
password: req.body.password,
admin: false
});
newUser.save(function(err){
if(err){
return next(err);
}
res.status(201).send("User Inserted)");
})
});
Related
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 });
}
})
})
i have this code:
i want to have another fields with the user like their phone number, but I don't know how I can add them
const userSchema = new mongoose.Schema({
username: String,
password: String
//// here i want to add another property
});
userSchema.plugin(passportLocalMongoose);
const User = mongoose.model('user', userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
and my registering is this:
User.register({ username: req.body.username }, req.body.password, function (err) {
if (err) {
console.log(err);
res.redirect("/register");
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/");
});
}
});
I don't know where to add the new field
You're almost there! I would recommend to add the field within your schema.
const userSchema = new mongoose.Schema({
username: String,
password: String
phoneNumber: String,
});
Then on your register call you will pass the data into the User.register method.
const user = {
username: req.body.username,
phoneNumber: req.body.phoneNumber,
}
User.register(new User(user), req.body.password, function (err) {
// your callback logic
Whenever I try to execute the below code using POSTMAN, it shows me an error.
I even tried adding the create adapter by using "let create user = await User.create etc.." but it is still showing error.
Code
//Controller file content
module.exports = {
register: function(req, res){
data = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
description: req.body.description
};
console.log(data);
User.create(data)
.fetch()
.exec((err) => {
if(err){return res.serverError(err);}
});
}
I don't understand if the code is wrong or maybe I am missing something. Please help.
You could try:
register: function(req, res){
data = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
description: req.body.description
};
console.log(data);
User.create(data)
.exec((err, user) => {
if(err){return res.serverError(err);}
else {res.send(user)}
});
}
Or:
register: async function(req, res){
data = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
description: req.body.description
};
console.log(data);
const user = await User.create(data)
.intercept(err => new Error(err))
.fetch();
return res.send(user);
}
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');
});
});