Mongoose 相关联 数据 创立与其他相关操作

前言

基于 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正常定义,再引入即可)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值