Mongoose Express.js删除具有关系的对象

时间:2017-04-14 12:25:08

标签: javascript mongodb express mongoose

所以我有schema Town,我想删除一个包含所有广告的城镇以及所有与广告相关的关系。这是我的模式:

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('/');
        }
    })

实际上一切正常,一切都被删除了,但是它会让我错误(当我试图删除带有广告的城镇时)在控制台中并停留在重定向上。这是错误:

  

(node:10200)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):CastError:强制转换为ObjectId,值为#34;城镇"在路径" _id"对于模特" Town"   (node:10200)DeprecationWarning:不推荐使用未处理的拒绝承诺。将来,未处理的承诺拒绝将使用非零退出代码终止Node.js进程。

1 个答案:

答案 0 :(得分:0)

问题在于重定向路径。它应该像else范围中的那个:

            res.redirect('/');
相关问题