node.jsexpressmongooseexpress-graphql

Do not work .map() to mapping all data which I get from database in mongoose and express-graphql


I get all data in mongoose using .find() and try to mapping this data in express and express-graphql. So .find() work correctly and return all data but when I try to use .map() for mapping all data does not work for me with this error: Expected Iterable, but did not find one for field"RootQuery.products".

Can anyone help me please?

Here is my schema.js file

const { buildSchema } = require('graphql')
module.exports = buildSchema(`
    type User{
        _id: ID!
        firstname: String!
        lastname: String!
        email: String!
        phone: Int!
        imageUrl: String!
        password: String!
        filtered: FilteredType
        isVerified: Boolean
        createdAt: String!
        updatedAt: String!
        message: String
    }
    type Product{
        _id: ID!
        title: String!
        description: String
        imageUrl: String
        price: Int!
        quantity: Int!
        locations: [String!]!
        category: String!
        seller: SellerType!
    }
    type FilteredType{
        category:String
        location: String,
      price(
            minPrice: Float, 
            maxPrice: Float
        ):Float  
    }
    type SellerType{
        id: User!,
        sellerPhone: Int!
    }
    type RootQuery{
        products: [Product!]
    }
    schema {
        query: RootQuery
    }
`);

Here is my resolver.js file

module.exports = {
   products: async (args, req) => {
        try {
            const products = await Product.find()
            if (!products) {
                const error = new Error("Could not find product!");
                error.statusCode = 404;
                throw error;
            }
            return {
                Product: products.map((product) => {
                    return { ...product._doc , _id: product._id.toString() }
                })
            }
        }
        catch (err) {
            throw err;
        }
    }
}


Solution

  • I think the issue is that you are writing Map with uppercase m, try this

    module.exports = {
       products: async (args, req) => {
            try {
                const products = await Product.find()
                if (!products) {
                    const error = new Error("Could not find product!");
                    error.statusCode = 404;
                    throw error;
                }
                return {
                    Product: products.map((product) => {
                        return { ...product._doc , _id: product._id.toString() }
                    })
                }
            }
            catch (err) {
                throw err;
            }
        }
    }