const mongoose = require("mongoose");
const { Schema } = mongoose;
// Database connection setup
main()
.then(() => {
[Link]("Connection successful");
})
.catch((err) => [Link](err));
async function main() {
await [Link]("mongodb://[Link]:27017/relationDemo");
}
// Order schema
const orderSchema = new Schema({
item: String,
price: Number,
});
// Customer schema with reference to orders
const customerSchema = new Schema({
name: String,
orders: [
{
type: [Link],
ref: "Order", // Reference to the Order model
},
],
});
// Models
const Order = [Link]("Order", orderSchema);
const Customer = [Link]("Customer", customerSchema);
// Function to insert orders into the database
const addOrders = async () => {
const res = await [Link]([
{ item: "Samosa", price: 12 },
{ item: "Chips", price: 10 },
{ item: "Chocolate", price: 40 },
]);
[Link]("Orders added:", res);
};
// Function to add a customer and link orders to them
const addCustomer = async () => {
const order1 = await [Link]({ item: "Chips" });
const order2 = await [Link]({ item: "Samosa" });
// Create a new customer and associate orders
const cust1 = new Customer({
name: "Rahul Kumar",
orders: [order1._id, order2._id], // Add the ObjectId of orders
});
const result = await [Link]();
[Link]("Customer added:", result);
};
// Function to show customer with their orders populated
const showCustomerWithOrders = async () => {
const customer = await [Link]({ name: "Rahul Kumar" })
.populate("orders"); // Populating orders field
[Link]("Customer with Orders:", customer);
};
// Run functions in the correct sequence:
// 1. Add orders to the database (run once)
// addOrders();
// 2. Add a customer and link orders (only after orders are added)
// addCustomer();
// 3. Show the customer with their orders populated
showCustomerWithOrders();