猫鼬快递.js删除有关系的对象



所以我有架构城镇,我想删除一个包含所有广告的城镇以及与广告的所有关系。以下是我的架构:

let adSchema = mongoose.Schema (
{
    author: {type: ObjectId, ref: 'User'},
    category: {type: ObjectId, ref: 'Category', required: true},
    town: {type: ObjectId, ref: 'Town', required: true},
}

(;

let categorySchema = mongoose.Schema (
{
    name: {type: String, required:true, unique: true},
    ads: [{type: ObjectId, ref: 'Ad'}]
}

(;

let townSchema = mongoose.Schema (
{
    name: {type: String, required:true, unique:true},
    ads: [{type: ObjectId, ref: 'Ad'}]
}

(;

let userSchema = mongoose.Schema(
{
    email: {type: String, required: true, unique: true},
    ads: [{type: ObjectId, ref: 'Ad'}],
}

(;

我正在使用此代码来执行此操作:

let id = req.params.id;
    Town.findByIdAndRemove(id).populate('ads').then(town => {
        let ads = town.ads;
        if (ads.length !== 0) {
            ads.forEach(ad => {
                Ad.findByIdAndRemove(ad.id).populate('author category').then(ad => {
                    let author = ad.author;
                    let category = ad.category;
                    let authorIndex = author.ads.indexOf(ad.id);
                    let categoryIndex = category.ads.indexOf(ad.id);
                    category.ads.splice(categoryIndex,1);
                    category.save(err => {
                        if (err) console.log(err);
                    });
                    author.ads.splice(authorIndex, 1);
                    author.save().then(() => {
                        res.redirect('towns');
                    })
                })
            });
        } else {
            res.redirect('/');
        }
    })

实际上一切都在工作,所有内容都按原样删除,但它在控制台中抛出错误(当我尝试删除带有广告的城镇时(并卡在重定向上。这是错误:

(节点:10200( 未处理的承诺拒绝警告:未处理的承诺拒绝(拒绝 ID:1(:强制转换错误:模型"城镇"的路径"_id"处的值"towns"强制转换为 ObjectId 失败 (节点:10200(弃用警告:不推荐使用未处理的承诺拒绝。将来,未处理的承诺拒绝将以非零退出代码终止 Node.js 进程。

问题出在重定向路径上。它应该类似于 else 范围内的那个:

            res.redirect('/');

最新更新