所以我要架構鎮,我想刪除一個城市,在它的所有廣告和所有relashionships到ads.Here是我的模式:貓鼬Express.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('/');
}
})
其實一切工作,一切都被刪除,因爲它應該是,但它把我的錯誤(當我試圖刪除城市,在它的廣告)在控制檯和停留在redirecting.This是錯誤:
(node:10200) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): CastError: Cast to ObjectId failed for value "towns" at path "_id" for model "Town" (node:10200) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.