问题描述
我想知道是否有区别,或者apollo-server
中通过mongoose
查询mongodb
的最佳实践是什么
I am wondering if there is a difference, or what is best practice in an apollo-server
to query mongodb
via mongoose
从上下文中获取模型:
import User from './User'
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
context: ({ req, res }) => ({
req,
res,
User,
}),
getUser(parent, args, context, info) {
return context.User.findOne({ _id: args.id})
},
VS
import User from './User'
getUser(parent, args, context, info) {
return User.findOne({ _id: args.id})
},
推荐答案
无论使用哪种ORM或查询构建器,都最好通过上下文将依赖项注入解析器.
Inject dependencies to resolver via context is better no matter what ORM or query builder you are using.
-
易于测试.我们可以为
User
创建模拟对象并轻松使用它.遵循依赖倒置的原理.
Easy to test. We can create mocked object for
User
and use it easily. Follow the principle of dependency inversion.
如果您有很多解析器,则无需为每个解析器导入User
.只需将其导入到初始化上下文的文件中一次即可.初始化上下文的模块在一个文件中管理,而不是分散在各处
If you have many resolvers, you don't need to import User
for each resolver. Just import it once in the file where to initialize the context.The modules for initializing the context are managed in one file instead of scattered everywhere
某些模块可能只需要初始化一次,然后将实例传递给上下文.
Some modules may only need to be initialized once and pass the instance to context.
这篇关于从上下文vs导入获取模型-Apollo Server Express&猫鼬的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!