我正在尝试从mongodb中的子文档中提取对象。结构如下(来自db.users.find().pretty()
):
{
"_id" : ObjectId("56a660b42819b770b89950bd"),
"userName" : "someGuy",
"itemCollection" : [
{
"item_name" : "item1",
"_id" : ObjectId("56a661232819b770b89950be")
}
],
"__v" : 13
}
此代码:
var userID = req.user._id;
var transactionID = req.body._id;
console.log('userID: '+userID);
console.log('transactionID: '+transactionID);
User.findByIdAndUpdate(
userID,
{$pull: {'itemCollection': {'_id': transactionID}}},{new: true}, function(err, model){
if(err){
console.log('ERROR: ' + err);
}
console.log(model);
});
获取以下输出:
> userID: 56a660b42819b770b89950bd
> transactionID: 56a661232819b770b89950be
> { itemCollection:
[ { item_name: 'item1',
_id: 56a661232819b770b89950be } ],
__v: 13,
userName: 'someGuy',
_id: 56a660b42819b770b89950bd }
所以似乎没有发生任何事情。我已经尝试了我能找到的堆栈溢出的每个变化,但它永远不会删除它。有人看到了什么问题吗?
答案 0 :(得分:0)
您需要将_id
从字符串转换为ObjectID
类型:
var mongoose = require('mongoose');
var userID = mongoose.mongo.ObjectID(req.user._id);