'mongoose Model.create function returns undefined

The above query returns a 200 when I try to create a User, but whenever I log into MongoDB there is no collections created. Can anyone help ?

//user model


const userSchema = mongoose.Schema({
    name: {
        type : String, 
        required  : true,
        trim : true
    },
    email: {
        type: String,
        required: true,
        unique: true,
        lowercase: true,
        validate: value => {
            if(!validator.isEmail(value)){
                throw new Error({error : 'Invalid email address'})
            }
        }
    },
    password: {
        type: String, 
        required: true,
        minLength: 5
    },
    // a user can have multiple jobs
    jobs : [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Job'
    }],
    tokens: [{
        token: {
            type: String,
            required:  true
        }
    }]
})
const User = mongoose.model('User', userSchema)
module.exports = User

// user functions written

  createUser(name, email, password){
        return User.create({name: name, email: email, password : password}, (err, docs) => {
            if(err){
                throw err.message;
            }

        });
    }

//routes.js

// user create
router.post('/users', async(req, res) => {
    try{
        const {name, email, password } = req.body
        const user = userManager.createUser(name, email, password); [1]
        res.status(200).json(user)
    }
    catch(error) {
        res.status(400).send({error : error.message})
    }
})

The line[1] returns undefined. Why ? note : all module requirements are fulfilled



Solution 1:[1]

After you create the schema you need to create a Model FROM that schema.

Example from MDN:

// Define schema
var Schema = mongoose.Schema;

var SomeModelSchema = new Schema({
  a_string: String,
  a_date: Date
});

// Compile model from schema
var SomeModel = mongoose.model('SomeModel', SomeModelSchema );

Now after you create the model you can use SomeModel.create

EDIT: line[1] will always return undefined because you are using callbacks and only way to get value out of callback is either push another callback(I would really discourage that). But best way is to use Promises now mongoose by default supports `Promises. So, basically for promises it will be,

// user functions written

async function createUser(name, email, password){
  try {
    return await User.create({ name: name, email: email, password: password });
  } catch (err) {
    throw err.message;
  }
}

In the router adda await:

const user = await userManager.createUser(name, email, password);

Solution 2:[2]

The problem is you call an asynchronous function synchronously. It returned undefined because the function hasn't been resolved yet. A solution could be to use promises or async/await.

Example:

async createUser(name, email, password) {
    const createdUser = await User.create({name,email,password});
    return creaatedUser;
}

Solution 3:[3]

Something I ran into was you need to pass in an empty object if your not setting any fields - i.e.

Good: Model.create({})

Bad: Model.create()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Danny