Reputation: 649
I'm a web development rookie and I'm trying to build a simple editable image gallery. I have a Collections schema and a Paintings schema:
var collectionSchema = new mongoose.Schema({
name: String,
paintings: [
{
type: Schema.Types.ObjectId,
ref: "Painting"
}
]
})
&&
var paintingSchema = new mongoose.Schema({
img: String,
description: String,
index: Number,
parent: String
});
I'm currently trying to add a destroy route which will delete one painting from one collection. I have this so far:
app.delete("paintings/:type/:index", function(req,res){
var type = req.params.type;
var index = req.params.index;
Painting.findOneAndRemove({parent:type,index:index},function(err,removedPainting){
if(err){
console.log(err);
} else{
res.redirect("/paintings/"+type);
}
});
});
However, I also need all of the "index" attributes of objects with higher indices than that of the deleted object to decrement by one after the object is deleted. Any idea as to what the best way to do this is?
I have tried:
changing the destroy route into an update route, and then just completely replacing the array of Paintings within the Collection to an updated version, but that doesn't seem to work--I think because the array within the Collection schema is not actually an array of objects, but an array of ObjectIds?
Redirecting (from end of the destroy route) to an update route which loops through the Paintings found by Paintings.find({parent: type}) and increments their ids, but I never actually got to test this because when I tried to redirect from the destroy route I would always get the error: "cannot GET paintings/:type/:index/delete" even though I had made the route a put request, not a get request.
Any ideas? Anything would be much appreciated, I'm clearly kind of fumbling around in the dark here. Thanks a ton!
Upvotes: 2
Views: 2939
Reputation: 649
Fixed this by eliminating the index attribute of the Painting schema, and eliminating the Painting schema entirely so that all paintings only exist as an object within Collections:
var collectionSchema = new mongoose.Schema({
name: String,
paintings: [
{
img: String,
description: String,
parent: String
}
]
})
Then, I changed my delete route so that it was actually a put route which pulled the correct painting from the Collection's painting array:
//DESTROY
app.put("paintings/:type/:index/delete", middleware.isLoggedIn, function(req,res){
var type = req.params.type;
var index = req.params.index;
Collection.findOne({name:type},function(err,collection){
if(err){
console.log(err);
} else{
var idOfRemove = collection.paintings[index]._id;
Collection.findOneAndUpdate({name:type},{$pull:{ paintings:{ _id: idOfRemove}}}, function(err,removedPainting){
if(err){
console.log(err);
} else{
res.redirect("/paintings/"+type);
}
})
}
})
});
Upvotes: 1