Last active
November 3, 2023 10:08
-
-
Save sourabhbagrecha/9699007e61100bd91ec5db148f49ae12 to your computer and use it in GitHub Desktop.
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 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hello sir,
how to solve this :
Then how to populate field of using Car
means
we can get data of Insurance but how to get data of Carval schemaa