static is not a function - mongoose

Viewed 44

I get the error "product.try() is not a function"

If I immediately invoke the try() it works ok, and node recognize the model "product".

is there something I d'ont understand about how mongoose works? I run the whole code in the one file and I followed the steps of the tutor from the video in the course I take.

what is the problem? thank you.

file: product.js =>

 const mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost:27017/shopApp')
    .then(()=>{
        console.log('CONNECTION OPEN!!!')
    })
    .catch(err=>{
        console.log('HO NO ERROR!!!')
        console.log(err)
    })
    
 
    const productSchema = new mongoose.Schema({
        name: {
            type: String,
            required: true,
            maxlength: 20   // Schema options
        },
        price: {
            type: Number, 
            min: [0, 'Price must be positive']
        },
        onSale: {
            type: Boolean,
            default: false
        },
        categories: {
        type: [String]
        }, 
        qty: {
            online: {
                type: Number,
                default: 0
            },
            inStore: {
                type: Number,
                default: 0
            }
        },
        size: {
            type: String,
            enum: ['S', 'M', 'L'] 
        }
    })
    
    const product = mongoose.model('product', productSchema); 
    
    productSchema.statics.try = function(){
        console.log('OK')
    };
    
    product.try();
1 Answers

You actually need tadd the .try function before calling mongoose.model()

This should work for you:

// connect to mongose...
// ... 

const productSchema = new mongoose.Schema({ /* .. your schema ..  */})
 
// add the function to the schema before creating the model!
productSchema.statics.try = function () {
  console.log('OK')
};


// since everything is added create the product model!
const product = mongoose.model('product', productSchema);

product.try();  // should work now.

Note: The .model() function makes a copy of schema. Make sure that you've added everything you want to schema, including hooks, before calling .model()!

docs

Related