2017-04-14 88 views
0

所以我要架构镇,我想删除一个城市,在它的所有广告和所有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.

回答

0

的问题是重定向path.It应该像一个在别的范围:

  res.redirect('/');