gpt4 book ai didi

node.js - 同时利用 GraphQL 和 Mongoose

转载 作者:太空宇宙 更新时间:2023-11-04 03:03:52 25 4
gpt4 key购买 nike

是否可以同时利用 GraphQL 和 Mongoose?

到目前为止,我已经能够集成 GraphQL 和 Mongoose 来处理数据库填充,但我很难理解它如何检索数据,特别是具有嵌套引用的数据。

考虑这个架构:

const fooSchema = new Schema({
name: { type: 'String', required: true },
bar: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Bar',
required: false,
}],
});

Bar 架构本质上是相同的,只有一个“name”字段。

是否可以运行 GraphQL 查询来使用“bar”中的引用填充数据?

目前,我们正在使用 GraphQL-Tools 来创建 typeDefs、Mutations 和 Queries,如下所示:

const typeDefs = `
type Foo {
name: String!,
bars:[Bar]
}
type Bar {
_id: ID,
name: String,
}

type Query {
allFoos: [Foo!]!
foo(_id: ID!): Foo
}

type Mutation {
...
}
`;
module.exports = makeExecutableSchema({typeDefs, resolvers});

最后一个查询指令如下所示:

const allFoos = async (root, data) => {
return await Foo.find({});
};

我可以更改查询指令以使用 .populate() 来获取 Bar,但这实际上并没有最终填充结果,我认为这是因为 typeDef 的设置方式所致。

那么是否有可能使这两个概念一起发挥作用?两者同时使用是否有意义?

最佳答案

正如他们所描述的 GraphQL:

GraphQL is a query language for your API, and a server-side runtime for executing queries by using a type system you define for your data. GraphQL isn't tied to any specific database or storage engine and is instead backed by your existing code and data.

Mongoose 在哪里

Writing MongoDB validation, casting and business logic boilerplate is a drag. That's why we wrote Mongoose

Monogoose 使用 mongodb 验证,而 graphql 是 API 的查询语言。

您可以从 here 阅读基本示例关于使用 Node、Express 和 Mongoose 设置简单的 GraphQL 服务器。

这两个是完全不同的。 Mongoose 在您对数据库执行任何操作时工作,而 grpgl 在您调用 API 时出现。 Graphql 验证您的 API 输入参数和返回参数。如果您将这两个添加到单个应用程序中。效果会很好。

  1. Mongoose 将验证您的数据库操作。
  2. GraphQL 将验证您的 API 输入和输出参数。

关于node.js - 同时利用 GraphQL 和 Mongoose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46414494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com