Mongoose更新推送,删除数组

时间:2016-02-14 20:19:52

标签: mongodb mongoose

我有一个猫鼬模型:

var schema = new Schema({
    loginName: {
        type: String,
        unique: true,
        required: true
    },
    hashedPassword: {
        type: String,
        required: true
    },
    salt: {
        type: String,
        required: true
    },
    created: {
        type: Date,
        default: Date.now
    },
    rooms: [{ _id: Schema.Types.ObjectId, loginName: [{ type: String }] }]
});

示例结果:

{
    _id: "56c0a986eeb118741109a45f",
    loginName: "MegaDaddgy",
    hashedPassword: "*****",
    salt: "******",
    __v: 10,
    rooms: [
        {
            _id: "56c0a986eeb118741109a461",
            loginName: [
                "MegaDaddgy"
            ]
        },
        {
            _id: "56c0d9e332f6ddc80ec7271c",
            loginName: [
                "MegaDaddgy"
            ]
        }
    ],
    created: "2016-02-14T16:21:26.272Z"
}

我需要什么:

  1. 在每个用户文档中搜索字段:rooms._id
  2. 在每个找到的用户文档中的数组loginName中推送新的loginName
  3. 删除数组中的所选loginName
  4. 示例参数:

    1. rooms._id:56c0a986eeb118741109a461
    2. loginName:" John"
    3. 结果:

      {
          _id: "56c0a986eeb118741109a45f",
          loginName: "MegaDaddgy",
          hashedPassword: "*****",
          salt: "******",
          __v: 10,
          rooms: [
              {
                  _id: "56c0a986eeb118741109a461",
                  loginName: [
                      "MegaDaddgy", "John"
                  ]
              },
              {
                  _id: "56c0d9e332f6ddc80ec7271c",
                  loginName: [
                      "MegaDaddgy"
                  ]
              }
          ],
          created: "2016-02-14T16:21:26.272Z"
      }
      

      示例参数:

      1. rooms._id:56c0a986eeb118741109a461
      2. loginName:" John"
      3. 结果:

        {
            _id: "56c0a986eeb118741109a45f",
            loginName: "MegaDaddgy",
            hashedPassword: "*****",
            salt: "******",
            __v: 10,
            rooms: [
                {
                    _id: "56c0a986eeb118741109a461",
                    loginName: [
                        "MegaDaddgy"
                    ]
                },
                {
                    _id: "56c0d9e332f6ddc80ec7271c",
                    loginName: [
                        "MegaDaddgy"
                    ]
                }
            ],
            created: "2016-02-14T16:21:26.272Z"
        }
        

        我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以通过$push

John推送到loginName数组中
Model.update({'rooms._id': ObjectId('56c0a986eeb118741109a461')}, 
    {$push: {'rooms.$.loginName': 'John'}}, function(...));

John数组中删除loginName$pull

Model.update({'rooms._id': ObjectId('56c0a986eeb118741109a461')}, 
    {$pull: {'rooms.$.loginName': 'John'}}, function(...));