1

私は次のようなスキーマを持っています(簡略化):

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]
});

サンプルドキュメントは次のようになります。

{
  "name": "My Org",
  "permissions" : [
    {"_id" : "joe@gmail.com", "role" : "admin"},
    {"_id" : "mary@gmail.com", "role" : "member"}
  ]
}

org.permissions.remove(req.params.email)以下のコンテキストに示すように、コマンドを使用して、アクセス許可行の1つを削除しようとしています。

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);
      });
    });
};

これを行うと、次のエラーが発生します。

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)

私が考えることができる唯一のことは、MongooseがObjectIDではない_idフィールドをサポートしていないということですか?これは奇妙なことです。コードの他の場所でこれらを使用していて、正常に機能しているからです(たとえば、org.permissions.id( "joe@gmail.com")は機能します)。

どんな提案も大歓迎です!

4

2 に答える 2

10

そこを使用しても機能しない理由はわかりませんが、 and演算子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
      ...
    });
};
于 2013-01-09T19:58:28.610 に答える