Ad

Nested Mongoose Queries Data Not Showing On GraphQL Query

- 1 answer

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(),
    }
Ad

Answer

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

Ad
source: stackoverflow.com
Ad