-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay22.js
76 lines (61 loc) · 1.8 KB
/
Day22.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
66
67
68
69
70
71
72
const express = require('express');
const mongoose = require('mongoose')
const app = express();
mongoose.connect('mongodb://127.0.0.1:27017/productDatabase')
.then(() => console.log("database connection successful"))
.catch((err) => console.error("connection error: ", err))
//schemas
const productSchema= new mongoose.Schema({
name: {
type:String,
required: true,
},
price: {
type:String,
required: true,
},
quantity: {
type:Number,
required: true,
},
publishedDate: {
type:Date,
default: Date.now
},
});
//models
const Product = mongoose.model("Product", productSchema)
//Creates a new product in MongoDB---------------------------------
async function createProduct(){
const product = new Product({
name: 'Earbirds',
price: '2000',
quantity: 5,
isPublished: true
});
const result = await product.save()
console.log(result)
}
createProduct();
//Retrieves all products from MongoDB-----------------------------
async function getAllProducts(){
const Products = await Product.find()
console.log(Products)
}
getAllProducts();
//Updates a product in MongoDB------------------------------------
async function updateProduct(id){
let product = await Product.findById(id)
if(!product) return;
product.name= 'EarPhones'
product.price = '3000'
const updatedProduct = await product.save()
console.log(updatedProduct)
}
updateProduct('65d6f752e196e2eaa0029512');what
//Deletes a product from MongoDB--------------------------------
async function deleteProduct(id){
let product = await Product.findByIdAndDelete(id)
console.log(product)
}
deleteProduct('65d6f752e196e2eaa0029512');