【问题标题】:Mongoose Express.js delete object with relationshipsMongoose Express.js 删除具有关系的对象
【发布时间】:2017-09-10 17:02:41
【问题描述】:

所以我有城镇模式,我想删除一个城镇,其中包含所有广告以及所有与广告的关联。这是我的模式:

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)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 id:1):CastError:对于模型“Town”的路径“_id”处的值“towns”,CastError:转换为 ObjectId 失败 (节点:10200)DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。

【问题讨论】:

    标签: javascript mongodb express mongoose


    【解决方案1】:

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

                res.redirect('/');
    

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      相关资源
      最近更新 更多