10
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

1
  • 2
    how we're supposed to know what User is?
    – Aᴍɪʀ
    Commented Jan 29, 2017 at 19:30

15 Answers 15

15

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'
});
2
  • can you give an example on kexjs for postgresql i'm getting the same error user .findone isn't a function , and i don't know where to start to look for this problem
    – user11042502
    Commented Feb 23, 2019 at 10:58
  • 1
    Sorry @sasharomanov. I don't know how to get it on postgresql. But make sure you are acquiring the model where you are using .findOne Commented Feb 24, 2019 at 17:47
5

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.

3

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

2

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

2
  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 !

2

You can try this:

user.collection.findOne(...)
1
  • For me the above is the way to use said method but most of internet says user.findOne(...) is legal. I don't get it. Commented Aug 31, 2022 at 16:03
1

use

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

instead of

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

In my case the problem was that instead of writing the below code

module.exports = UserModel;

I had wrote

 exports.module = UserModel;
0

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

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

0

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.

0

Just check this out...

const mongoose = require("mongoose");
const UserSchema = mongoose.Schema({
    username : {
        type : String,
        required : true
    },
    password : {
        type : String,
        required : true
    },
}, {timestamps : true});

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

For me it was a import mistake i was importing like this

const User = require("../models/user.js")

const User = require("../models/account.js")

in the routes file but i imported user and account schema in a new models/index.js file and then impoted in the routes file like this

const { User, Account } = require("../models/index.js")

and the it worked perfectly fine.

-1

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 !

1
  • 1
    Why -1 ? Please give an explanation that would clarify the reason
    – Bonjour123
    Commented Feb 18, 2019 at 16:20
-1

In my case I defined User like this ↓

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

instead of ↓

const User = require('../../models/User')
1
  • That means you defined User not as a Model, but as a string, no?
    – samdouble
    Commented Sep 17, 2020 at 17:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.