javascript - Mongoose Express.js delete object with relationships -
so have schema town , want delete 1 town ads in , relashionships ads.here schemas:
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'}], }
);
i using code this:
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('/'); } })
actually working , deleted should throw me error(when trying delete town ads in it) in console , stuck on redirecting.this error:
(node:10200) unhandledpromiserejectionwarning: unhandled promise rejection (rejection id: 1): casterror: cast objectid failed value "towns" @ path "_id" model "town" (node:10200) deprecationwarning: unhandled promise rejections deprecated. in future, promise rejections not handled terminate node.js process non-zero exit code.
the problem in redirecting path.it should 1 in else scope:
res.redirect('/');
Comments
Post a Comment