I’m trying to seed data for my db but both my schema reference each other so I’m not sure how it’s possible to seed one before the other.
I want to use fakerjs to have some data to play with, but I’m a bit confused how I’d approach it.
Here are my Schemas, they’re super simple and both ref each other:
import mongoose from "mongoose";
import { loadType } from "mongoose-currency";
const Schema = mongoose.Schema;
loadType(mongoose);
const CategorySchema = new Schema(
{
name: String,
expenses: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Expense",
},
],
},
{ timestamps: true, toJSON: { getters: true } }
);
const Category = mongoose.model("Category", CategorySchema);
export default Category;
And the other:
import mongoose from "mongoose";
import { loadType } from "mongoose-currency";
const Schema = mongoose.Schema;
loadType(mongoose);
const ExpenseSchema = new Schema(
{
name: String,
price: {
type: mongoose.Types.Currency,
currency: "USD",
get: (v) => v / 100,
},
date: {
type: Date,
},
category: {
type: mongoose.Schema.Types.ObjectId,
ref: "Category",
},
},
{ timestamps: true, toJSON: { getters: true } }
);
const Expense = mongoose.model("Expense", ExpenseSchema);
export default Expense;
Does anyone know how I’d go about seeding them if they both rely on each other?
2
Answers
This is what I landed at thanks to the answer above:
Not sure if this is most efficient, if anyone knows a better way, please lmk!
Refs to children documentation explains this situation.
E.g. ("mongoose": "^7.3.1")
Debug logs: