0% found this document useful (0 votes)
5 views2 pages

Orderid

Uploaded by

hspandit071
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Orderid

Uploaded by

hspandit071
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

const mongoose = require("mongoose");

const { Schema } = mongoose;

// Database connection setup


main()
.then(() => {
console.log("Connection successful");
})
.catch((err) => console.log(err));

async function main() {


await mongoose.connect("mongodb://127.0.0.1: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: Schema.Types.ObjectId,
ref: "Order", // Reference to the Order model
},
],
});

// Models
const Order = mongoose.model("Order", orderSchema);
const Customer = mongoose.model("Customer", customerSchema);

// Function to insert orders into the database


const addOrders = async () => {
const res = await Order.insertMany([
{ item: "Samosa", price: 12 },
{ item: "Chips", price: 10 },
{ item: "Chocolate", price: 40 },
]);
console.log("Orders added:", res);
};

// Function to add a customer and link orders to them


const addCustomer = async () => {
const order1 = await Order.findOne({ item: "Chips" });
const order2 = await Order.findOne({ 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 cust1.save();


console.log("Customer added:", result);
};
// Function to show customer with their orders populated
const showCustomerWithOrders = async () => {
const customer = await Customer.findOne({ name: "Rahul Kumar" })
.populate("orders"); // Populating orders field
console.log("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();

You might also like