Mongoose est un Object Document Mapping Library, l'equivalent de sequelize pour mysql.

npm i --save mongoose
const mongoose = require("mongoose")
mongoose.connect("mongodb+srv://6ssou:[email protected]/
shop?retryWrites=true&w=majority")
.then(() => {
app.listen(3000);
}).catch(err => {
console.log(err)
})
CREATE SCHEMA
// models/product.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const productSchema = new Schema({
title: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
description: {
type: String,
required: true
},
imageUrl: {
type: String,
required: true
},
userId: {
type: Schema.Types.ObjectId,
ref: 'User'
}
})
// to connect the model to a name
// mongoose will take this name, turn it into lowerCase then plural
// this will be the collection name !
module.exports = mongoose.model('Product', productSchema);
SAVE DATA :
exports.postAddProduct = (req, res, next) => {
const title = req.body.title;
const imageUrl = req.body.imageUrl;
const price = req.body.price;
const description = req.body.description;
// here we pass an object with key: value pairs
const product = new Product({
title: title,
price: price,
description: description,
imageUrl: imageUrl,
userId: req.user
})
product
// save is provided by mongoose!
.save()
.then(() => {
res.redirect('/admin/products');
})
.catch(err => {
console.log(err);
});
};
RETRIEVE DATA
exports.getProducts = (req, res, next) => {
// we use find here wich is provided by mongoose
Product.find()
.then(products => {
console.log(products)
res.render('shop/product-list', {
prods: products,
pageTitle: 'All Products',
path: '/products'
});
})
.catch(err => {
console.log(err);
});
};
FIND BY ID
C'est la même méthode qu'avec mongodb classique :
Product.findById(prodId).then( .. .. )
EDIT BY ID :
exports.postEditProduct = (req, res, next) => {
const prodId = req.body.productId;
const updatedTitle = req.body.title;
const updatedPrice = req.body.price;
const updatedImageUrl = req.body.imageUrl;
const updatedDesc = req.body.description;
// when we call save on a existing product, it updates it
Product.findById(prodId).then(product => {
product.title = updatedTitle,
product.pricen = updatedPrice,
product.description = updatedDesc,
product.imageUrl = updatedImageUrl
// product.save is created by mongoose
return product.save()
}).then(() => {
res.redirect('/admin/products');
})
.catch(err => console.log(err));
};
DELETE BY ID :
exports.postDeleteProduct = (req, res, next) => {
const prodId = req.body.productId;
// Product.findByIdAndRemove(prodId)
Product.deleteOne({_id: mongodb.ObjectId(prodId)}).then(result => {
res.redirect("/admin/products")
})
.catch(err => console.log(err));
};
CREATE A USER MODEL
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
cart: {
items: [{
productId: {
type: Schema.Types.ObjectId,
ref: 'Product',
required: true
},
quantity: {
type: Number,
required: true
}
}]
}
});
module.exports = mongoose.model("User", userSchema)
//app.js
// Get user
app.use((req, res, next) => {
User.findById("5ed0dff41f49081c9c3d7872")
.then(user => {
req.user = user
console.log(req.user)
next();
})
.catch(err => console.log(err));
});
db().then(result => {
User.findOne().then(user => {
if(!user) {
const user = new User({
name: 'Satoshi',
email: '[email protected]',
cart: {
items: []
}
});
user.save();
}
})
app.listen(3000)