-
Notifications
You must be signed in to change notification settings - Fork 1
/
day23.js
65 lines (57 loc) · 2.01 KB
/
day23.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const mongoose = require('mongoose');
// Step 1: Define schemas for Category and Product
const categorySchema = new mongoose.Schema({
name: String,
description: String,
});
const productSchema = new mongoose.Schema({
name: String,
price: Number,
quantity: Number,
category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' },
});
// Step 2: Create models for Category and Product
const Category = mongoose.model('Category', categorySchema);
const Product = mongoose.model('Product', productSchema);
// Step 3: Function to generate random products associated with the "fruits" category
async function generateRandomProducts(numProducts) {
try {
// Check if the "fruits" category exists, if not, create it
let fruitsCategory = await Category.findOne({ name: 'fruits' });
if (!fruitsCategory) {
fruitsCategory = await Category.create({
name: 'fruits',
description: 'Category for fruits',
});
}
// Generate random products associated with the "fruits" category
const products = [];
for (let i = 0; i < numProducts; i++) {
const product = await Product.create({
name: `Fruit ${i + 1}`,
price: Math.random() * 10 + 1, // Random price between 1 and 10
quantity: Math.floor(Math.random() * 10) + 1,
category: fruitsCategory._id,
});
products.push(product);
}
console.log('Random products generated:', products);
} catch (error) {
console.error('Error generating random products:', error);
}
}
// Example usage:
(async () => {
try {
// Connect to MongoDB
await mongoose.connect('mongodb+srv://kushalagrawal779:[email protected]/?retryWrites=true&w=majority', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('Connected to MongoDB');
// Call the function to generate random products
await generateRandomProducts(10); // Generate 10 products in the "fruits" category
} catch (error) {
console.error('Error:', error);
}
})();