passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
(req, email, password, done) => {
// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(() => {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'email' : email },function(err, user){
// if there are any errors, return the error
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null, false, {'errorMessages': 'That email is already taken.'});
} else {
// if there is no user with that email
// create the user
let newUser = new User();
// set the user's local credentials
newUser.name = req.body.fullname;
//newUser.email = email;
newUser.password = newUser.generateHash(password);
// save the user
newUser.save((err)=>{
if (err)
return done(err);
return done(null, newUser);
});
}
});
});
}));
The above code is in node js using passport js authentication and the code of local-signup is not working.
In the above code i am getting the error:
User.findOne() is not a function
.
My schema is all right... please help
You need to (if you're not already) create instance of your data with a model
like
var UserDetails = mongoose.model('userInfo', UserDetail);
Now you should be able to use .findOne
here.
And make sure you're defining structure for your date inside a collection like..
var Schema = mongoose.Schema;
var UserDetail = new Schema({
username: String,
password: String
}, {
collection: 'userInfo'
});
Kindly, use the code below
module.exports = User = mongoose.model('user', UserSchema)
User should be the model name and remember to define const UserSchema = new Schema
at the top to create a new model in MongoDB and
user should the route where you have the
router.post('/user') (req, res) => { code here }
with this, you are exporting the mongoose schema to the route user, this which enables findOne
to be seen as a mongoose function.
maybe you did not export the Model from your User model folder. eg: module.exports = User = mongoose.model("users", UserSchema);
Export the user Model from models directory from file named user.js.
module.exports.User = User
Then Load User model from any other
const {User} = require('../models/user.js');
Note : I'm assuming user models file is named user.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With