Mongoose 模式静态与方法

问题描述 投票:0回答:2

在猫鼬模式中,我们可以通过两种方式创建方法:SchemaName.methods.fuctionNameSchemaName.statics.functionName。 静态更容易使用,我只需要调用ModelName.Fuction。方法需要创建对象才能使用。我的问题是它们之间有什么不同。 静态方法的优点和缺点是什么。什么时候应该使用 statics 以及什么时候应该使用 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)
    }
})
mongoose-schema
2个回答
6
投票

statics对象包含与模型本身关联的函数,而不是与单个实例关联的函数。使用statics的一个优点是我们不需要访问类的实例来访问与其关联的功能。例如:在上面的代码片段中,您尝试搜索用户。您正确实现了 static 成员。如果您使用了方法,您将需要实例化一个用户对象来搜索用户。 当您已经实例化对象时,请使用 methods;当您不会实例化对象时,请使用 statics


0
投票

思考这个问题最简单的方法就是思考

this

statics
方法中,
this
指的是模型模式,而在
methods
方法中,
this
指的是文档实例。

例如,您可以使用

statics
方法来运行如下查询:

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

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

这将为您返回一份文件列表。您可以使用

methods
方法来扩充文档,如下所示:

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()

官方文档里还有几个例子:

© www.soinside.com 2019 - 2024. All rights reserved.