Home > OS >  Mongose method is not a function
Mongose method is not a function

Time:10-14

I am using mongoose and every time I try to use a method that I created for a schema, it throws the following error message:

UnhandledPromiseRejectionWarning: TypeError: findItem.updatePrice is not a function

Model definition and instance creation:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/shopApp')
.then(()=>{
    console.log('Working!');
})
.catch(err=>{
    console.log('Error');
    console.log(err);
})

const productSchema = new mongoose.Schema({
 name: {
     type: String,
     required: true
 },
 price: {
     type: Number
 }
}) 
const product = mongoose.model('product', productSchema);
const bike = new product({name:'MTB', price: 599});

productSchema.methods.updatePrice = function(newprice){
    this.price = newprice;
    return this.save();
}

const updatedPrice = async ()=>{
    const findItem = await product.findOne({name:'MTB'});
    await findItem.updatePrice(500);
}
updatedPrice();

CodePudding user response:

The example in the docs defines the instance methods before creating an instance of it.

productSchema.methods.updatePrice = function(newprice){
    this.price = newprice;
    return this.save();
}

const product = mongoose.model('product', productSchema);
const bike = new product({name:'MTB', price: 599});
  • Related