1

I'm trying to create an API using Apollo-server with GraphQL and Mongoose. My problem is that the query to Mongoose does return the data, but the GraphQL model shows as null when I test.

I've tried different methods and using promises.

    type Articulo {
        id: ID
        nombre: String
        codigoDeBarras: String
        codigo: String
    }
    type EntradaInventario {
        id: ID
        articulo: Articulo
        inventario: Inventario
        cantidad: Float
    }
    type Almacen {
        id: ID
        nombre: String
    }
    type Inventario {
        id: ID
        almacen: Almacen
        nombre: String
    }
    type Query {
        articulo(codigoDeBarras: String): Articulo
        entradaInventario(inventario: String): [EntradaInventario]
    }
    type Mutation {
        addEntradaInventario(idArticulo: String, idInventario: String, cantidad: Float): EntradaInventario
        addAlmacen(nombre: String): Almacen
        addInventario(idAlmacen: String, nombre: String): Inventario
    }
    const EntradaInventarioModel = Mongoose.model("EntradaInventario", {
    _id: Schema.Types.ObjectId,
    idArticulo: {type: Mongoose.Schema.Types.ObjectId, ref: 'Articulo'},
    idInventario: {type: Mongoose.Schema.Types.ObjectId, ref: 'Inventario'},
    cantidad: Number
}, "entradainventarios");

    Query: {
        articulo: (_, args) => ArticuloModel.findOne({
            'codigoDeBarras': args.codigoDeBarras
        }).exec(),
        entradaInventario: (_, args) => 
            EntradaInventarioModel.find({idInventario: args.inventario})
            .populate('idArticulo')
            .exec(),
    }

1 Answer 1

2

You shouldn't use the populate on the Parent model. You should instead define how to query the nested model in the EntradaInventario resolvers.

Inventory should look something like this:

Inventory : {
    articulo: async (parent, args, { }) => {
      return await Articulo.findOne({
        _id: parent.idArticulo,
      });
    },
  }

Here is a repo that does just that and is a good example https://github.com/the-road-to-graphql/fullstack-apollo-express-mongodb-boilerplate

Sign up to request clarification or add additional context in comments.

3 Comments

should inventory be a new query or be inside the entradaInventario resolver?
your entradaInventario query should just have the EntradaInventarioModel.find({idInventario: args.inventario}) command. The EntradaInventario type should have a resolver of how to query articulo and inventario fields on that type
GraphQL will know to go the resolvers of EntradaInventario to fetch the articulo and inventario

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.