Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const mongoose = require("mongoose");
const claimSchema = mongoose.Schema({
billed_insurances: [
{ type: mongoose.Schema.Types.ObjectId, ref: "Insurance" },
],
});
const Claim = mongoose.model("Claim", claimSchema);
const insuranceSchema = mongoose.Schema({
name: String,
});
const Insurance = mongoose.model("Insurance", insuranceSchema);
// You should use a npm package like dotenv to manage your environment variables
// instead of hardcoding your connection string in the code directly.
mongoose.connect(process.env.MONGODB_URI);
const main = async () => {
// Inserting Sample Insurance Documents
const insertedInsurances = await Insurance.insertMany([
{ name: "Lorem" },
{ name: "Ipsum" },
{ name: "Dolor" },
{ name: "Sit" },
]);
// Creating an array of Insurance IDs
const insertedInsuranceIds = insertedInsurances.map(
(insurance) => insurance._id
);
// Inserting a Sample Claim Document
const insertedClaim = await Claim.create({
billed_insurances: insertedInsuranceIds,
});
console.log(insertedClaim);
// Output
// {
// billed_insurances: [
// new ObjectId("62bbe0968c7777b4c0ce0db2"),
// new ObjectId("62bbe0968c7777b4c0ce0db3"),
// new ObjectId("62bbe0968c7777b4c0ce0db4"),
// new ObjectId("62bbe0968c7777b4c0ce0db5")
// ],
// _id: new ObjectId("62bbe0968c7777b4c0ce0db8"),
// __v: 0
// }
// Populating the Claim Document with the Insurances using the array of ObjectIDs
const popluatedClaim = await Claim.findById(insertedClaim._id).populate({
path: "billed_insurances",
});
console.log(popluatedClaim);
// Output
// {
// _id: new ObjectId("62bbe0968c7777b4c0ce0db8"),
// billed_insurances: [
// { _id: new ObjectId("62bbe0968c7777b4c0ce0db2"), name: 'Lorem', __v: 0},
// { _id: new ObjectId("62bbe0968c7777b4c0ce0db3"), name: 'Ipsum', __v: 0},
// { _id: new ObjectId("62bbe0968c7777b4c0ce0db4"), name: 'Dolor', __v: 0},
// { _id: new ObjectId("62bbe0968c7777b4c0ce0db5"), name: 'Sit', __v: 0 }
// ],
// __v: 0
// }
};
main();
@engrpeters
Copy link

++

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment