When registering, my user doesn't get saved to the database. Does anyone know what is going wrong here?
Schema + model:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/testusers', {useNewUrlParser: true});
const Schema = mongoose.Schema;
let userSchema = new Schema({
steamId: String,
username: String,
avatar: String,
tradelink: String,
balance: Number,
});
let userModel = mongoose.model('User', userSchema);
Find and save:
userModel.findOne({ steamId: profile.id } , (err,user) => {
if(!user) {
let newUser = new userModel({steamId:profile._json.steamid, username: profile._json.personaname,avatar: profile._json.avatar, tradelink: '', balance:0});
console.log(newUser);
newUser.save((err,user) =>{
console.log(err);
console.log('created user');
return done(err,user);
});
}
else {
console.log('user exists');
return done(err,user);
}
});
Collection data (empty after save): https://prnt.sc/rmlsc2
Console output:
PS C:****> node app.js
(node:26628) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
{
_id: 5e7b78aae3903a680486cb13,
steamId: '76561198126366365',
username: 'BaeWolfy',
avatar: 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d3/d36a7d04988b8730a0a75516a7dbfa24ee1a45fc.jpg',
tradelink: '',
balance: 0
}
null
created user
Made a stupid mistake in the connection string I used localhost instead of my atlas cluster connection string. It is working now.
Related
I am trying to save record into mongodb using node.js and for that purpose I am using mongoose driver but here I am unable to insert record into mongodb. I am explaining my code below.
mongo.util.js:
const mongoose = require('mongoose').Mongoose;
const config = require('../../config/settings');
const mongooseInstance = new mongoose();
const url = `mongodb://${config.MONGO_USER}:${config.MONGO_PWD}#${config.MONGO_URL}/${config.MONGO_DB}`;
const options = {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
};
/*
1- Connect to mongo server
*/
mongooseInstance.connect(url, options, (err) => {
if(!err) {
console.log('Mongodb connection successed');
} else {
console.log('Error in DB connection:' + JSON.stringify(err, undefined, true));
}
})
module.exports = mongooseInstance;
This file is my connection file where I can connect to my local mongodb. This file has included into mt app.js file and I am getting the message as Mongodb connection successed.
users.model.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const User = new Schema({
name: {type: String},
mobile: { type: String},
password: { type: String},
email: { type: String},
city: { type: String}
}, {
timestamps: {
CreatedAt: 'CreatedAt',
UpdatedAt: 'UpdatedAt'
}
});
module.exports = mongoose.model('customers', User);
The above file is my schema file where I am trying to design schema for customer collection.
users.service.js:
const _ = require('lodash'),
axios = require('axios'),
model = require('../model/users.model');
async registerUser(req) {
try{
const data = req.body;
console.log('data', data);
const user = await model.create(data);
if (!user) {
return {
data: user,
error: true,
msg: 'User Registeration failed'
}
}else {
return {
data: user,
error: false,
msg: 'User Registered successfully'
}
}
}catch(error) {
console.log('Error in registerUser service::', error);
}
}
Here I trying to insert the record but when this function is called no record is inserting into mongodb even no customer collection is there. Here I need to insert record using this mongoose driver.
Try as below
Step 1: create object out of User model
var user = new model(req.body)
Step 2: then call
user.save(function(){})
I'm trying to save data in the MongoDB atlas with node.js and mongoose.
Every time I use MySchema.save(), Data is inserting But I'm also getting the error:
UnhandledPromiseRejectionWarning: MongoWriteConcernError: No write concern mode named 'majority;' found in replica set configuration
Also, there is no duplicate entry, Data is also inserting But I'm also getting the error
let User = require('../models/users.models');
const username = req.body.username;
const newUser = new User({username});
newUser.save()
.then(() => res.json('user added!'))
.catch(err => res.status(400).json('Error: ' + err));
User model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
},
},
{
timestamps: true
});
const User = mongoose.model('User', userSchema);
module.exports = User;
I know it was asked 2 months ago, but for those who will encounter the same issue.
You are mistakenly entering a wrong char at the end of the URI string:
mongodb+srv://${ user }:${ password }#track-mkahl.mongodb.net/test?retryWrites=true&w=majority;
You need to delete the ; after the word majority.
This helped me.
const schema = new Schema({ name: String }, {
writeConcern: {
w: 'majority',
j: true,
wtimeout: 1000
}
});
https://mongoosejs.com/docs/guide.html#writeConcern
"mongoURI" : "mongodb+srv://${ user }:${ password }#cluster0.mde0j.mongodb.net/cluster0?retryWrites=true&w=majority "
I get the same error with this in default.json its simple error just delete the &w=majority part at the end and it will be solved
for me it was also in the URI string like #Yossi Saadi has suggested, it's just that I had majoritys written there instead of majority
I think there's something wrong with this line.
let User = require('../models/users.models');
I have created a solution for you.
/models/user.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
mongoose.connect("mongodb://localhost/stack-overflow", { useNewUrlParser: true })
var userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
},
},
{
timestamps: true
});
const User = mongoose.model('User', userSchema);
module.exports = User
/routes/userroute.js
const User = require("../models/user")
// Imagine run() as an asynchronous request handler
async function run() {
try {
const user1 = new User({ username: "lidafafnus" })
user1.save((err,result) => {
console.log(err, result)
})
} catch(error) {
console.log(error)
}
}
run()
I'm creating an application using node js. in this application i already completed user login and registration via passport js. So now i need to provide access to the logged user to change there password. So i'm trying to do this in my own way but when i run this process the changed password doesn't updated and save it to the logged user's mongoose document. I'll provide the code that i used to that process. So i'm requesting you guys please let me know how can i do this in with my program.
This is my POST route for the change password.
app.post('/changePass/:hash', isLoggedIn, function(req, res){
cph.findOne({hash: req.params.hash}).populate('userId', "local.password -_id").exec(function(err, hash){
if(err) throw err;
if(validator.isEmpty(req.body.currentPassword) || validator.isEmpty(req.body.newPassword) || validator.isEmpty(req.body.confirmPassword)){
res.render('admin/settings/pages/cup/cpf', {
user: req.user,
message: 'Fields must be required',
data: hash
});
}
else {
if(!bcrypt.compareSync(req.body.currentPassword, hash.userId.local.password)){
res.render('admin/settings/pages/cup/cpf', {
user: req.user,
message: 'Current password is incurrect',
data: hash
});
}
else {
if(req.body.newPassword != req.body.confirmPassword){
res.render('admin/settings/pages/cup/cpf', {
user: req.user,
message: 'New password and confirm password do not match',
data: hash
});
}
else {
cph.update({$set:{'userId.local.password': bcrypt.hashSync(req.body.confirmPassword, bcrypt.genSaltSync(8), null)}}, function(){
console.log('Success')
});
}
}
}
});
});
This is the mongoose collection that creating a hash to change the password sending as a combined link to the logged user's email.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var cpHashSchema = Schema({
userId: {
type: Schema.ObjectId,
ref: 'users'
},
hash: {
type: String
}
});
module.exports = mongoose.model('changepasswordHash', cpHashSchema);
This is the user's collection
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var userSchema = Schema({
active: {
type: Boolean,
default: false
},
first: {
type: String
},
last: {
type: String
},
email: {
type: String
},
local: {
username: {
type: String
},
password: {
type: String
}
},
joined: {
type: Date,
default: Date.now
},
usertype: {
type: String,
default: 'user'
}
});
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
module.exports = mongoose.model('users', userSchema);
These are the source code that i'm using to build this application. So guys please help me to complete this application.
thank you
First of all - you trying to update changepasswordHash collection with fields from another table. MongoDB couldn't update related records.
You have to update users collection using userId something like:
users.update({_id: hash.userId._id}, {$set: {'local.password': newPass}}, callbackHere)
I have installed mongodb and my mongodb and db folders are C:/mongoDB/bin and C:/data/db respectively. I have also setup admin user as stated on
https://docs.mongodb.com/manual/tutorial/enable-authentication/
Now i want to perform basic CRUD operations requiring both read and write on a database mApp through Express and Mongoose. I am providing code for both app and schema below.
Code is well documented so that it is easy to understand.
App.js
var express = require('express');
var app = express();
//Invoking user
var User = require('./schema.js');
//Creating an employee object by giving values to all properties
var User1 = new User({
name: 'Anurag',
username: 'Anurag2',
password: 'abc',
admin: false,
location: 'somewhere',
meta: {
age: 25,
website: 'abc.com'
},
createdAt: 'Jun 11 2017',
updatedAt: 'Jun 11 2017'
}); //Remember to provide all records,otherwise document wont be saved.
//CRUD start. Creating a user document
User1.save(function(err, employ, num) {
if (err) {
console.log('error occurred');
}
console.log('saved ' + num + ' record');
console.log('Details ' + employ);
});
/* To retrieve documents from database, you can retrieve all at
once, or one at a time by find(), findById(), findOne() */
//To retrieve all documents
User.find({}, function(err, data) {
if (err) {
console.log('error occurred while retrieving all docs');
}
console.log(data);
});
User.findOne({
username: 'Anurag2'
}, function(err, data) {
if (err) {
console.log('error in finding one document');
}
console.log(data);
});
User.update({
location: 'someplace'
}, {
location: 'anything'
}, function(err) {
if (err) {
console.log('error in updating');
}
console.log('updated');
});
//update one document
User.findOneAndUpdate({
username: 'Anurag2'
}, {
admin: true
}, function(err, data) {
if (err) {
console.log('error in finding and updating');
}
console.log('updated' + data);
});
//Delete a user document
User.remove({
location: 'anywhere'
}, function(err) {
if (err) {
console.log('error occurred');
}
console.log('removed');
});
DB Schema(schema.js)
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mApp'); //myApp is the database being connected here.
//now we open a connection
var db = mongoose.connection;
db.once('open', function() {
console.log('Connected to Database');
});
db.on('error', console.error.bind(console, 'connection error'));
//initialising a schema
var Schema = mongoose.Schema;
mongoose.Promise = require('bluebird'); //used as mpromise was showing deprecated on console.
//creating a schema
var userSchema = new Schema({
name: String,
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
Required: true
},
admin: Boolean,
location: String,
meta: {
age: Number,
website: String
},
createdAt: Date,
updatedAt: Date
});
//creating a model that uses this schema
var User = mongoose.model('User', userSchema);
//now we export this model
module.exports = User;
Now, I login in mongo through admin and i changed the db to mApp. I run the app through node.
The mongod console shows I am not authorized to perform any actions on the app.
No query gets executed and I get all error messages. Why is this happening? Please help me with this.
You have been enable authentication for your database.
So, you have to provide the corresponding credentials in your connection string
Change:
mongoose.connect('mongodb://localhost/mApp');
To
mongoose.connect('mongodb://username:password#host:port/database');
More information on mongoose documentation
I have a mongoose schema that looks like this:
var userSchema = new Schema({
username: {type: String, required: true, index: {unique: true}},
usernameCanonical: {type: String, required: true, index: {unique: true}}
});
userSchema.pre("save", function () {
this.usernameCanonical = this.username.toLowerCase();
return next();
});
I want to be able to create new users by only entering a username, and let usernameCanonical get generated by the model automatically.
var user = new User({
username: "EXAMPLE_USERNAME"
});
user.save()
When I try to do this I get a validation error from mongoose saying that usernameCanonical is required.
Path `usernameCanonical` is required.
The problem seems to be that the pre-save hooks get called after validation. I don't want to have to manually add a canonical username every time I save a new user. I also don't want to remove the required option from the schema.
Is there some way to get a mongoose model to automatically generate a required field? Adding a default value to the usernameCanonical field in the schema seems to prevent the validation error, but it feels like a hack.
As levi mentioned, you should use the validate() hook:
Save/Validate Hooks
Check this working example based on your code:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {type: String, required: true, index: {unique: true}},
usernameCanonical: {type: String, required: true, index: {unique: true}}
});
userSchema.pre('validate', function () {
if ((this.isNew || this.isModified) && this.username) {
this.usernameCanonical = this.username.toLowerCase();
}
});
const User = mongoose.model('user', userSchema);
mongoose.connect('mongodb://localhost:27017/uniqueTest')
.then(() => {
// create two users
const user1 = new User({
username: 'EXAMPLE_USERNAME-1'
});
const user2 = new User({
username: 'EXAMPLE_USERNAME-2'
});
return Promise.all([
user1.save(),
user2.save()
]);
})
.then(() => {
// update username
return User.findOne({ username: 'EXAMPLE_USERNAME-1' })
.then((user) => {
user.username = 'EXAMPLE_USERNAME_UPDATED-1';
return user.save();
});
})
.then(() => mongoose.connection.close())
.then(() => console.log('script finished successfully'))
.catch((err) => {
console.error(err);
mongoose.connection.close()
.then(() => process.exit(1));
});
I hope this helps.