Node.js Mongoose,从数组中删除对象并更新其他对象
我是一名网络开发新手,我正在尝试建立一个简单的可编辑图像库。我有一个收藏模式和一个绘画模式:Node.js Mongoose,从数组中删除对象并更新其他对象,node.js,mongodb,express,mongoose,mongoose-schema,Node.js,Mongodb,Express,Mongoose,Mongoose Schema,我是一名网络开发新手,我正在尝试建立一个简单的可编辑图像库。我有一个收藏模式和一个绘画模式: var collectionSchema = new mongoose.Schema({ name: String, paintings: [ { type: Schema.Types.ObjectId, ref: "Painting" } ] }) && 我目前正在尝试添加一个销毁路径,它将从一个
var collectionSchema = new mongoose.Schema({
name: String,
paintings: [
{
type: Schema.Types.ObjectId,
ref: "Painting"
}
]
})
&&
我目前正在尝试添加一个销毁路径,它将从一个收藏中删除一幅画。到目前为止,我有:
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);
}
});
});
但是,我还需要索引高于已删除对象的所有对象的“索引”属性在删除对象后递减1。你知道最好的方法是什么吗
我试过:
有什么想法吗?任何事情都将不胜感激,我显然是在黑暗中摸索。非常感谢 通过消除绘画模式的索引属性,并完全消除绘画模式,使所有绘画仅作为收藏中的对象存在,从而修复了此问题:
var collectionSchema = new mongoose.Schema({
name: String,
paintings: [
{
img: String,
description: String,
parent: String
}
]
})
然后,我更改了删除路径,使其实际上是一个put路径,它从集合的绘画数组中提取正确的绘画:
//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);
}
})
}
})
});
为什么要修改其他绘画的索引属性,这似乎是个坏主意。你需要index属性做什么,也许有另一种方法可以在不将其作为属性存储在文档中的情况下获取它。因为我无法使集合架构用于删除和更新路由,所以我不得不使用类似于绘画的东西。findOneAndUpdate({parent:type,index:index})来更新绘画,所以我首先需要一个索引参数来找到这幅画。在试图修改这一点时,我不确定如何使用绘画收藏阵列中的位置编辑或删除绘画。拥有索引参数非常有用,因为它允许我构建索引,并围绕有序索引(而不是ID)显示页面。我不需要唯一的id,因为每个图库只对其创建者/所有者可见。
//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);
}
})
}
})
});