Insert data from javascript file into mongodb using graphql

Viewed 18

I am new to using Graphql and MongoDB. I am trying to insert data from an existing javascript file where the data has been defined. I was trying to use a mutation in order to achieve this but I have no clue what I'm really doing. Any help would be nice.

const dotenv = require('dotenv');

dotenv.config();

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

const { MongoClient } = require('mongodb');

const  items  = require('./itemsListData');



    const typeDefs = gql`
    type Query {

      items:[Item!]!

    }

    
    type Item{
      id:ID!,
      name:String!,
      aisle:String!,
      bay:String!,
      price:Float!,
      xVal:Int!,
      yVal:Int!
    }
    type Mutation {
        createItem(name: String!, aisle: String!): Item!
    }
`;
   



console.log(items)

const resolvers = {

Query:  {

 items:() => items,

  },


Item:{

id: ( { _id, id }) => _id || id,

},


Mutation: {
  createItem: async(_, { name }, { db }) => {
    //  name:String!, bays:[Bay!]!, xStartVal:Int!, xEndVal:Int!, yStartVal:Int!, yEndVal:Int!
    const newItem = {
        items
    }

    // insert Item object into database
    const result = await db.collection('Items').insert(newItem);
    console.log("This is the result " + result);
    return result.ops[0]; // first item in array is the item we just added
  }
}



};




const start = async () => {

  const client = new MongoClient("mongodb+srv://admin:admin@quickkartcluster.o0bsfej.mongodb.net/test", { useNewUrlParser: true, useUnifiedTopology: true });
  

  await client.connect();

  const db = client.db("QuickKart");
  

 

  const context = {

    db,

  }

  

  const server = new ApolloServer({

      typeDefs,

      resolvers,

      context,

      introspection: true

  }); 


  // The `listen` method launches a web server.
  server.listen().then(({ url }) => {
    console.log(`  Server ready at ${url}`);
});


}



start();

here is my javascript data file

https://pastebin.com/wvGANBgR

0 Answers
Related