试图删除Mongoose中的子文档给我一个内部的猫鼬错误

Sco*_*zer 1 mongoose mongodb node.js express

我有一个如下的架构(简化):

var Permission = new Schema({
  _id: String,  // email address
  role: String  // "admin" or "member"
});

var Org = new Schema({
  name: {type: String, index: {unique: true, dropDups: true}, trim: true},
  permissions: [Permission]
});
Run Code Online (Sandbox Code Playgroud)

示例文档如下所示:

{
  "name": "My Org",
  "permissions" : [
    {"_id" : "joe@gmail.com", "role" : "admin"},
    {"_id" : "mary@gmail.com", "role" : "member"}
  ]
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用该命令删除其中一个权限行org.permissions.remove(req.params.email),如下面的上下文所示:

exports.removePermissions = function(req, res) {
  var name = req.params.name;
  return Org
    .findOne({name: name})
    .select()
    .exec(function(err, org) {
      if (err) return Org.handleError(res, err);
      if (!org) return Org.handleError(res, new Error("#notfound " + name));
      org.permissions.remove(req.params.email);
      org.save(function(err, org) {
        if (err) return Org.handleError(res, err);
        else return res.send(org);
      });
    });
};
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我收到以下错误:

TypeError: Cannot use 'in' operator to search for '_id' in joe@gmail.com
    at EmbeddedDocument.Document._buildDoc (/../node_modules/mongoose/lib/document.js:162:27)
    at EmbeddedDocument.Document (/../node_modules/mongoose/lib/document.js:67:20)
    at EmbeddedDocument (/../node_modules/mongoose/lib/types/embedded.js:27:12)
    at new EmbeddedDocument (/../node_modules/mongoose/lib/schema/documentarray.js:26:17)
    at MongooseDocumentArray._cast (/../node_modules/mongoose/lib/types/documentarray.js:62:10)
    at Object.map (native)
    at MongooseDocumentArray.MongooseArray.remove (/../node_modules/mongoose/lib/types/array.js:360:21)
    at model.Org.methods.removePermissions (/../models/org.js:159:20)
Run Code Online (Sandbox Code Playgroud)

我唯一能想到的是Mongoose不支持不是ObjectID的_id字段?这很奇怪,因为我在我的代码中的其他地方使用它们并且它工作正常(例如org.permissions.id("joe@gmail.com")工作).

任何建议非常感谢!

Joh*_*yHK 10

我不确定为什么使用remove它不起作用,但你可以用findOneAndUpdate$pull操作员原子地做这个:

exports.removePermissions = function(req, res) {
  var name = req.params.name;
  return Org.findOneAndUpdate(
    {name: name}, 
    {$pull: {permissions: {_id: req.params.email}}},
    function(err, org) {
      // org contains the updated doc
      ...
    });
};
Run Code Online (Sandbox Code Playgroud)

  • 这个问题现在有点固定......但它仍处于预发布状态,3.6分支.虽然这是一个很大的错误...似乎我选择猫鼬而不是普通的mongo做出了糟糕的选择...... (2认同)