'User.findOne() is not a function

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



Solution 1:[1]

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'
});

Solution 2:[2]

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.

Solution 3:[3]

maybe you did not export the Model from your User model folder. eg: module.exports = User = mongoose.model("users", UserSchema);

Solution 4:[4]

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

Solution 5:[5]

  1. User.findOne is not a function error

    In my case:

  2. CORRECT SYNTAX: const User = require('../../models/User') // rectified

  3. Error occured due to VS code auto-format my import changed to below

    const User = require - '../../models/User' :- Though this import is the culprit, VS code still validated this import !

Solution 6:[6]

use

module.exports = User = mongoose.model("users", UserSchema);

instead of

module.exports = User => mongoose.model("users", UserSchema);

Solution 7:[7]

You can try this:

user.collection.findOne(...)

Solution 8:[8]

I also had this situation where:

const User = require('../../mongoose/User');
User.findOne(...);

returned 'findOne is not a function'

But by changing to:

var User = require('../../mongoose/User');
User.findOne(...);

..it worked. Hope I helped someone !

Solution 9:[9]

It is how you export and import your Model. If you are defining model as const User = mongoose.model("users", UserSchema); then exporting it by export default User;. you should use the following to import that:

import User from '../db/models/user';

instead of

const User = require('../db/models/user');

Solution 10:[10]

TRY THIS make sure you imported your schama as import User from '../db/models/user'; instead of const User = require('../db/models/user'); if you're using es6 syntax

Solution 11:[11]

If your error contains also something like Warning: Accessing non-existent property '...' of module exports inside circular dependency and TypeError: User.findOne is not a function, and generaly the model is an empty {}, then the problem may be the connection (import and export) of the both files. The file that exports the used model can most likely also import the destionation file where the model is used.

Example: Let us have 2 files, user - exporting the User model, and the receiver - example.js

user.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const exmple = require("./example"); //notice how the destination file is also imported in the sender model file

//... all your code and schema here

const User = mongoose.model('User', UserSchema);

module.exports = User;

example.js

const User = require("./user"); // circular dependency

//... your code

This mostly happens, as in my case, when having 2 model files, and importing, and exporting each one into another creating the error. I needed the export model for some User model functions.

Solution 12:[12]

In my case I defined User like this ?

const User = '../../models/User'

instead of ?

const User = require('../../models/User')