더이상 하지 않는 Backend - NodeJS/Node-Express 개론(완)
Express - 4장 : Mongoose 의 CRUD
VictorMeredith
2023. 3. 3. 14:05
1. CRUD란 ?
- create
- read
- update
- delete
2. Cheat Sheet
Schema 세팅
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
name: {
type: String,
required: true
},
brand: {
type: String,
required: false
},
order: {
type: Schema.Types.ObjectId,
ref: "Order"
}
});
// This creates our model from the above schema, using mongoose's model method
var Product = mongoose.model("Product", ProductSchema);
// Export the Article model
module.exports = Product;
연결하기
var mongoose = require("mongoose");
var db = require("./models");
mongoose.connect("mongo_URI", { useNewUrlParser: true });
Create
var product = { name: "Soda", brand: "demoBrand" };
db.Product.create(product)
.then(function(dbProduct) {
console.log(dbProduct);
})
.catch(function(err) {
console.log(err);
});
Read
db.Product.find({}) //모두찾기
db.Product.findOne({ _id: <id> }) //id로 찾기
db.Product.findById(id); // 스키마에서 id로 찾기
Update
db.Product.updateOne({ name: 'Soda' }, { brand: 'newBrand' });
db.Product.updateMany({ brand: 'demoBrand' }, { quantity: 500 }); //많은 문서 업데이트
Delete
db.Product.deleteOne({ name: 'Soda' });
db.Product.deleteMany({ quantity: { $gte: 100 } });
- 서버 다까먹겠다 ! 복습 달려 !