从对象ID数组中删除MongoDB的值

4

我有这篇文章在我的收藏中:

{
    "_id" : ObjectId("52718433e18a711923000005"),
    "owners" : [
        ObjectId("52718433e18a711923000004"),
        ObjectId("52ed40dccc5bc50000000003"),
        ObjectId("52ed4171abe2780000000003")
    ]
}

我有以下陈述,我试图从owners字段中删除一个值:

Business.update({_id:req.body._id}, {$pull:{"owners":req.body.userid}}, function(err){
    if(err){
        res.json(500, {message:"Could not remove user from admin list"});
    }else{
        res.json(200);
    }
});

我知道req.body._idreq.body.userid有合法的值:

{ _id: '52718433e18a711923000005',
  userid: '52ed4171abe2780000000003' }

其他操作,例如通过ID查找业务等都可以正常工作,因此这不是一个ObjectId格式问题。还可能是什么原因呢?

-- 编辑:这是我的(缩写的)模式定义:

var BusinessSchema = new Schema({
    business_name: {type: String, required: true},
    owners: {type: Array}
});

1
你能否更新你的问题,包括你的模式定义? - JohnnyHK
我已经把它添加到了问题中。 - Alex Polkhovsky
2个回答

3

您当前的模式不为Mongoose提供任何有关owners数组字段中包含的数据类型的信息。如果您希望Mongoose将您的字符串转换为ObjectID,则需要在模式中提供类型信息:

var BusinessSchema = new Schema({
    business_name: {type: String, required: true},
    owners: [{type: Schema.ObjectId}]
});

2

在尝试匹配值进行pull操作时,似乎需要将其转换为ObjectId。但是搜索时则不需要。因此可以采用以下方式:

var ObjectId = require('mongoose').Types.ObjectId;

Business.update({_id:req.body._id}, {$pull:{"owners": new ObjectId(req.body.userid)}}, function(err){
    if(err){
        res.json(500, {message:"Could not remove user from admin list"});
    }else{
        res.json(200);
    }
});

-- 编辑:如果我将模式从 owners: {type: Array} 更改为 owners: [Schema.Types.ObjectId],那么我就可以跳过转换,我的原始语句就可以工作。


1
需要将 String 强制转换为 ObjectId 才能满足 [{type: Schema.Types.ObjectId, ref: 'owner'}]。自2014年以来MongoDB / Mongoose有变化吗?还可能是 ref 干扰了强制转换吗? - Dänu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接