Apollo / Graphql,Postgres - 为什么这个查询返回null? [重复]

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

这个问题在这里已有答案:

enter image description hereenter image description here我正在使用apollo-graphql和postgres,现在我希望能够将我的后端数据提取到apollo客户端。它是我第一次尝试使用graphql而且我做了以下操作:i。)在localhost:4000上创建了apollo-graphql服务器,它也有apollo graphql playground ii。)为我的服务器定义了typeDefs和resolvers iii。)在typeDefs中 - >定义了我的schema iv。)在解析器中 - >只添加了一个findAll Query(尝试了两个属性,没有参数):

    Query: {
    me: () => account.findAll({attributes: ['user_id', 'username', 'email']})
}

v。)然后我将使用sequelize ORM定义的postgres dbIndex添加到服务器文件中(我在上面的步骤iv中用来查询我的数据库)

vi。)在我的dbIndex文件中,我使用环境变量对get db进行身份验证,获取连接消息,创建db模式并将其导出。

完成所有这6个步骤之后,在阿波罗游乐场,我看到了null。

我的文件列表如下:

Server.js:

const {ApolloServer} = require('apollo-server');

const typeDefs = require('./schema');

const {account} = require('../database/dbIndex.js');

const resolvers = {
    Query: {
        me: () => account.findAll()
    }
};

const server = new ApolloServer({
    typeDefs,
    resolvers
});

server.listen().then(({url}) => {
    console.log(`Server ready at ${url}`);
});

dbIndex.js

const Sequelize = require('sequelize');

require('dotenv').config();

const sortDb = new Sequelize(
    `${process.env.DATABASE}`,
    process.env.DATABASE_USER,
    process.env.DATABASE_PASSWORD,
    {
      dialect: 'postgres',
    },
);

sortDb
    .authenticate()
    .then(() => {
        console.log('Connected to DB');
    })
    .catch((err) => {
        console.error('Unable to connect to DB', err);
    });

const account = sortDb.define('account', {
    user_id: {type: Sequelize.INTEGER},
    username: {type: Sequelize.STRING},
    email: {type: Sequelize.STRING}
});

module.exports.account = account;

schema.js

const {gql} = require('apollo-server');

const typeDef = gql 
`
    type Query {
        "These are the queries we define in our query type"
        me(user_id: ID): User
    }
    "How to define the structure of user? Below is an object type that does this:"
    type User {
        user_id: ID,
        username: String,
        email: String
    }
`;

module.exports = typeDef;

请帮忙!提前致谢!

node.js postgresql graphql apollo
1个回答
1
投票

findSell中的findAll返回一个行数组,尝试使用特定查询或findById的findOne

它返回null,因为User类型的属性可以在数组中解析。

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