'Method expression is not of Function type (mongoose Model)

i came across this error today and did not find a fix for it.

const mongoose = require('mongoose');

const userSchema = mongoose.Schema({
    name: {type:String, required:false},
    birthday: {type:String, required:false},
    email: {type:String, required:false},
    hobbies: {type:String, required:false},
    picture: {type:String, required:false},
});


const User = mongoose.model("User",userSchema);
module.exports = User;

If you hover over Schema it will show the error : "Method expression is not of Function type" I later use this Schema here:

const User = require("../models/user");
exports.createUser = (req, res, next) => {
    const url = req.protocol + "://" + req.get("host");
    const user = new User({
        name: req.body.name,
        birthday: req.body.birthday,
        email: req.body.email,
        hobbies: req.body.hobbies,
        picture: req.body.picture
    });
    console.log(user);
    user
        .save()
        .then((createdUser) => {
            console.log(createdUser);
            res.status(201).json({
                message: "User added successfully",
            });
        })
        .catch((error) => {
            res.status(500).json({
                message: "Creating user failed!",
            });
        });
};

The console log of user is the following:

{
  name: 'Chris',
  birthday: 'test',
  email: 'test',
  hobbies: 'test',
  picture: 'test',
  _id: new ObjectId("61c0a908e340bcdec1011de5")
}

The _id should not contain new ObjectId and only the part in the brackets. I hope you can find a fix for this or an idea on how it should be done.



Solution 1:[1]

According to the latest Mongoose docs, if you redo it like so:

import mongoose from 'mongoose';
const { Schema } = mongoose;
const userSchema = new Schema ({
  ...
});

That should fix it, so you're creating a new instance of a Schema object, rather than calling a Schema "method".

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 Tyler2P