Last active
August 8, 2022 03:22
-
-
Save MubashirWaheed/67fed334bf1a1091f26f44d794d0ff90 to your computer and use it in GitHub Desktop.
This script is used to seed the mongodb without any seeding package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mongoose = require("mongoose"); | |
const Items = require("./models/Items"); | |
const Categories = require("./models/Categories "); | |
const { faker } = require("@faker-js/faker"); | |
// connect with mongodb | |
const uri = "add you mongodb uri here"; | |
const dbOptions = { | |
useNewUrlParser: true, | |
useUnifiedTopology: true, | |
}; | |
const DBconnection = async () => { | |
try { | |
await mongoose.connect(uri, dbOptions); | |
console.log("connected to db successfully"); | |
} catch (error) { | |
console.log("error", error); | |
} | |
}; | |
const createItem = async (name, price, stock, image_url) => { | |
console.log("name", name); | |
const item = new Items({ | |
name, | |
price, | |
stock, | |
image_url, | |
}); | |
try { | |
await item.save(); | |
} catch (error) { | |
console.log("inside createItem", error); | |
} | |
}; | |
const createCategories = async (name, description) => { | |
const categoryObj = { | |
name: name, | |
description: description, | |
}; | |
const category = new Categories(categoryObj); | |
try { | |
await category.save(); | |
} catch (error) { | |
console.log(error); | |
} | |
}; | |
const addItems = async () => { | |
try { | |
await createItem("apples", "2", 50, "https://random/image/1.jpeg"); | |
await createItem("pineapple", "2", 50, "https://random/image/2.jpeg"); | |
await createItem("car", "20", 7, "https://random/image/car.jpeg"); | |
await createItem("bear", "2", 50, "https://random/image/bear.jpeg"); | |
} catch (error) { | |
console.log("error from addItems fun: ", error); | |
} | |
}; | |
const addCategories = async () => { | |
try { | |
await createCategories("fruits", faker.lorem.lines(2)); | |
await createCategories("toys", faker.lorem.lines(3)); | |
} catch (error) { | |
console.log("from addCategories: ", error); | |
} | |
}; | |
const seedData = async () => { | |
try { | |
await DBconnection(); | |
await Promise.all([addItems(), addCategories()]); | |
console.log("database seeded successfully "); | |
mongoose.connection.close(); | |
} catch (error) { | |
console.log("error from seedData function", error); | |
} | |
}; | |
seedData(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment