Reputation: 75
There are plenty of projects out there that help to seed a MongoDB with NodeJS, but none that are natively TypeScript. What would be the best way to seed data programatically via TypeScript?
Upvotes: 1
Views: 2652
Reputation: 1
You need to build your project first, and then run the .js
version of your seed file. Here is an example of how you might set it up with scripts in your package.json
:
"scripts": {
"dev": "nodemon --exec ts-node './src/server.ts'",
"build": "rm -rf dist/ && tsc --project './tsconfig.build.json'",
"start": "pnpm build && NODE_ENV=production node --trace-warnings './dist/server.js'",
"watch": "tsc --project './tsconfig.build.json' --watch",
"db:seed": "pnpm build && node './dist/db/seed-database.js'",
"db:clear": "pnpm build && node './dist/db/seed-database.js -c'",
...
Upvotes: 0
Reputation: 423
I'm currently working on it, I have a seederScript that looks like this
require("dotenv").config();
import { ProductsData } from "./data/products"; //dummy data
import connectDB from "./config/db";
import Product from "./models/product";
connectDB();
const importData = async (): Promise<void> => {
try {
await Product.deleteMany({});
await Product.insertMany(ProductsData);
console.log("Data Import Success");
process.exit();
} catch (error) {
console.error("Error with data import", error);
process.exit(1);
}
};
importData();
and when I try to run this script with node node src/seederScript
I'm getting this error Cannot find module...
. I'm getting many different errors however I try and I don't know what is wrong
Upvotes: 1