Moe Thar
Moe Thar

Reputation: 41

Mongoose Schema statics vs methods

In a mongoose schema we can create the method as two way SchemaName.methods.fuctionName and SchemaName.statics.functionName. Statics is more easier to use I just need to call ModelName.Fuction. Methods need to create object to use. My question is what different between them. What is the advantage and disadvantage of statics and methods. When I should use statics and when I should use methods.

// Users.js
UserSchema.statics.findUserStatics = async function(mail) {
    var findUser = await User.findOne({ mail: mail })
    return findUser
}

UserSchema.methods.findUserMethods = async function(mail) {
    var findUser = await User.findOne({ mail: mail })
    return findUser
}

// router.js

const { User } = require('./../models/Users')
router.post('/findbyStatics', async (req, res) => {
    try {
        var result = await User.findUserbyStatics(req.body.mail);
        res.status(200).send(result)
    } catch (e) {
        res.status(400).send(e.message)
    }
})

router.post('/findbyMethods', async (req, res) => {
    try {
        var user = new User()
        var result = await user.findUserbyMethods(req.body.mail);
        res.status(200).send(result)
    } catch (e) {
        res.status(400).send(e.message)
    }
})

Upvotes: 4

Views: 2088

Answers (2)

David Newcomb
David Newcomb

Reputation: 10943

The easiest way to think about this is to think about this!

In a statics method the this refers to the model schema and in a methods method the this refers to the document instance.

For example, you might use a statics method to run a query like:

catSchema.statics.findGingerCats = function() {
  return this.find({colour: 'ginger'}) // this = catSchema
}

const Cat = model('cat', catSchema)
const gingerCats = Cat.findGingerCats()

This will give you back a list of documents. You can use a methods method to augment the document like so:

catSchema.methods.getAge = function() {
  return Date.now() - this.date_of_birth // this = document instance
}

const gingerCats = Cat.findGingerCats()
const age_of_first_ginger_cat = gingerCats[0].getAge()

There are a few more examples in the official documentation:

Upvotes: 0

Dane Williamson
Dane Williamson

Reputation: 71

The statics object contains functions that are associated with the model itself, and not the individual instances. An advantage of using statics is that we do not need access to an instance of the class in order to access the functionality associated with it. For example: in your code snippet above, you attempt to search for a user. You correctly implemented a static member. If you had used a method, you would have been required to instantiate a user object to search for a user. Use methods when you will have objects already instantiated, and use statics when you will not.

Upvotes: 7

Related Questions