前言
基于 Udemy The Web Development Bootcamp 2023 Section 44 Data Relationship With Mongo , Section 45 Mongo Relationships with Express, Section 46: YelpCamp: Adding the Reviews Model 的coding小总结。
正文:
如果在MongoDB中遇到俩个数据之间有联系如何用mongoose表达?在schema定义文件中:
cnost mongoose = require('mongoose');
const Review = require('./review'); //引用需要id的schema
const Schema = mongoose.Schema;
const CampSchema = new Schema({
title: String,
reviews: [{
type: Schema.Types.ObjectId,//此行永远不变
ref: 'review'
}]
});
CampSchema.post('findOneAndDelete', async function(doc) {
if(doc){
await Review.deleteMany({
_id:{ $in: doc.reviews}})}
} //如果findOne存在则删除里面所有reviews
module.exports = mongoose.model('Campground', CampSchema);
我们不用传递review.id 直接传递review。mongoose自动更改 如下图.push(review);bv
app.post('/campgrounds/:id/reviews', async (req, res) => {
const campground = await Campground.findById(req.params.id);
const review = new Review(req.body.review);
campground.reviews.push(review);
await review.save();
await campground.save();
res.redirect(`/campgrounds/${campground._id}`);
})
另,在添加附属物id后,如何在该物品删除后(post)删除所有附属物,见FindOndAndDelete. Review(附属物 schema正常定义,再引入即可)