Express 如何在mongoose中从数组中删除元素
我有以下模式:Express 如何在mongoose中从数组中删除元素,express,mongoose,Express,Mongoose,我有以下模式: // userSchema { _id: Schema.ObjectId, email: { type: String, unique: true }, password: String, boxes: [boxSchema] } // boxSchema { _id: Schema.ObjectId, boxId: { type: String, unique: true }, boxName: String } 我有这样的数据: { _id:
// userSchema
{
_id: Schema.ObjectId,
email: { type: String, unique: true },
password: String,
boxes: [boxSchema]
}
// boxSchema
{
_id: Schema.ObjectId,
boxId: { type: String, unique: true },
boxName: String
}
我有这样的数据:
{
_id: random,
email: em@i.l,
password: hash,
boxes: [{ "boxId" : "box1", "boxName" : "Box 1"},
{ "boxId" : "box2","boxName" : "Box 2"},
{ "boxId" : "box3","boxName" : "Box 3"}]
}
我正在尝试从boxId为box1的Box数组中删除一个元素,我尝试的代码如下:
User.findOne({
_id: req.body.id
})
.then(function (user) {
if (user) {
for (i in user.boxes)
if (user.boxes[i].boxId === 'box1')
user.boxes[i].remove();
res.json('removed');
}
})
.catch(function (err) {
....
});
但是,它会删除所有驻留的框,而不是boxId:box1使用
过滤器怎么样
User.findOne({
_id: req.body.id
})
.then(function (user) {
if (user) {
user.boxes = user.boxes.filter(function(box){
return box.boxId !== 'box1'
})
res.json('removed');
}
})
.catch(function (err) {
....
});
使用filter
User.findOne({
_id: req.body.id
})
.then(function (user) {
if (user) {
user.boxes = user.boxes.filter(function(box){
return box.boxId !== 'box1'
})
res.json('removed');
}
})
.catch(function (err) {
....
});
从数组中删除元素的方法有很多,如下所示:
1) Delete():使用此函数将删除元素,但不会更改数组大小,并在删除元素后保留空对象
2) splice():其工作原理类似于delete(),但在删除元素后删除数组中的空白位置
3) filter():它将函数作为参数,并有效地删除元素。从数组中删除元素的方法有很多,如下所示:
1) Delete():使用此函数将删除元素,但不会更改数组大小,并在删除元素后保留空对象
2) splice():其工作原理类似于delete(),但在删除元素后删除数组中的空白位置
3) filter():它将函数作为参数,并有效地删除元素