简体   繁体   English

Mongoose - 删除子文档数组项

[英]Mongoose - delete subdocument array item

I have this little schema for users:我为用户提供了这个小架构:

{
 username: String,
 contacts: Array
}

So for example some user's contacts will look like this:例如,某些用户的联系人将如下所示:

{
 username: "user",
 contacts: [{'id': ObjectId('525.....etc'), 'approved': false}, {'id':ObjectId('534.....etc'), 'approved': true}]
}

Now I need to delete an item from contacts so I do:现在我需要从联系人中删除一个项目,所以我这样做:

model.findByIdAndUpdate(23, {'$pull': {
              'contacts':{'id':'525.....etc'}
              }});

but seems not working, no errors but it doesn't gets deleted , I just would like to return this document for the user:但似乎不起作用,没有错误,但没有被删除,我只想为用户返回此文档:

{
     username: "user",
     contacts: [{'id':ObjectId('534.....etc'), 'approved': false}]
    }

how to achieve this?如何实现这一目标?

The $pull operator actually just performs the conditions on the array element on which it is operating. $pull操作符实际上只是在它所操作的数组元素上执行条件。 It seems that your question might not actually show that you are probably working with an ObjectId value that mongoose creates by default for all array fields.似乎您的问题实际上可能并未表明您可能正在使用ObjectId默认为所有数组字段创建的ObjectId值。

So you could to your query like this, after importing the ObjectId creation method:因此,在导入ObjectId创建方法后,您可以像这样查询:

model.findByIdAndUpdate(23, {
    '$pull': {
        'contacts':{ '_id': new ObjectId(someStringValue) }
    }
});

Or in fact you can actually define your "schema" a little better, and mongoose will actually "autocast" the ObjectId for you based on the "type" defined in the schema:或者实际上,您实际上可以更好地定义“架构”,并且猫鼬实际上会根据架构中定义的“类型”为您“自动转换”ObjectId:

var contactSchema = new Schema({
    approved: Boolean
});

var userSchema = new Schema({
    username: String,
    contacts: [contactSchema]
});

This allows mongoose to "follow the rules" for strictly typed field definitions.这允许 mongoose 对严格类型的字段定义“遵循规则”。 So now it knows that you actually have an _id field for each element of the contacts array, and the "type" of that field is actually an ObjectId so it will automatically re-cast "String" values supplied as a true ObjectId.所以现在它知道对于contacts 数组的每个元素实际上都有一个_id字段,并且该字段的“类型”实际上是一个ObjectId因此它会自动重新转换作为真正ObjectId 提供的“String”值。

finaly!终于!

MongoDB:

"imgs" : {"other" : [ {
        "crop" : "../uploads/584251f58148e3150fa5c1a7/photo_2016-11-09_21-38-55.jpg",
        "origin" : "../uploads/584251f58148e3150fa5c1a7/o-photo_2016-11-09_21-38-55.jpg",
        "_id" : ObjectId("58433bdcf75adf27cb1e8608")
                                    }
                            ]
                    },
router.get('/obj/:id',  function(req, res) {
var id = req.params.id;



Model.findOne({'imgs.other._id': id}, function (err, result) {
        result.imgs.other.id(id).remove();
        result.save();            
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM