简体   繁体   中英

How to add a custom method on a mongoose Model

In Mongoose, we can add methods to documents as follows:

const userSchema = new mongoose.Schema({
  balance: Number
})
userSchema.methods.withdrawBalance = function(amount){
  const doc = this
  doc.balance = doc.balance - amount
}

and we can use it as follows:

const userDoc = UserModel.findById(ID_HERE);
userDoc.deductBalance(100); // -100$ USD
userDoc.save()

I want to be able to do the same on the models the same way I can do it on documents, I want to be able to something like that:

const userDoc = UserModel.findById(ID_HERE).myCustomMethod()

But How?

Hm I am not sure if I get you right but lets try.

const Order = mongoose.model("Order", orderSchema);

Order.test = function(){
    console.log("Here I am!");
}

(async () => {
    const o = await Order.findOne({}).test();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM