$ pull整个2D数组行-猫鼬

时间:2020-05-20 16:17:13

标签: node.js mongodb mongoose

我能够$addToSet不用创建重复项的2d数组也没有问题,但是如果我想通过$pull从列表中删除项目,则永远不会从mongodb文档中删除该行。 2d数组的结构如下:

inviteGroup: {
    biddingUserId: { type: String, lowercase: true, trim: true },
    username: { type: String, lowercase: true, trim: true }
  },

除了下面的代码,我还尝试了$pull的代码行,其中req.body.userId代表上面模型中的biddingUserId

        $pull: { inviteGroup: { $in: [req.body.userId]} }

但这似乎没有用。如何删除二维数组行?感谢您的帮助!

以下是该集合在mongodb中的样子的屏幕快照,与模型匹配。 enter image description here

   Post.findByIdAndUpdate(
      { _id: req.params.id },
      {
        $pull: { inviteGroup: req.body.userInvited }
      },
      function (err, docs) {
        if (err) {
          console.log("err$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
          console.log(err);

          context.res = {

            status: 500,

            body: {
              message: "Add Invite Error!",
              error: err

            },

            headers: {
              "Access-Control-Allow-Credentials": "true",
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Methods": "PATCH, OPTIONS",
              "Access-Control-Allow-Headers": "Content-Type, Set-Cookie",
              "Access-Control-Max-Age": "86400",
              "Vary": "Accept-Encoding, Origin",
              "Content-Type": "application/json"
            }

          };

          context.done();



        } else {
          context.res = {

            status: 200,

            body: {
              message: "User Invited Successfully!",
              error: err

            },

            headers: {
              "Access-Control-Allow-Credentials": "true",
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Methods": "PATCH, OPTIONS",
              "Access-Control-Allow-Headers": "Content-Type, Set-Cookie",
              "Access-Control-Max-Age": "86400",
              "Vary": "Accept-Encoding, Origin",
              "Content-Type": "application/json"
            }

          };

          context.done();

        }
      });

3 个答案:

答案 0 :(得分:2)

这是工作示例-

收藏

{
    "_id" : ObjectId("5ecc1c6af2a26b884f4272eb"),
    "inviteGroup" : [
        [
            {
                "biddingUserId" : "3",
                "username" : "name3"
            },
            {
                "biddingUserId" : "2",
                "username" : "name2"
            }
        ],
        [
            {
                "biddingUserId" : "1",
                "username" : "name1"
            },
            {
                "biddingUserId" : "4",
                "username" : "name4"
            }
        ]
    ]

}

请注意使用双精度$ elemMatch到达嵌套数组,并使用位置运算符使用$ pull标识外部数组元素,以根据查询条件删除内部数组元素。

猫鼬代码

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
var db = mongoose.connection;
mongoose.set('debug', true);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
});
const InviteGroupSchema  = new mongoose.Schema({
   inviteGroup : [[{
    biddingUserId: { type: String, lowercase: true, trim: true },
    username: { type: String, lowercase: true, trim: true }
  }]]
})
const InviteGroup = mongoose.model('InviteGroup', InviteGroupSchema, 'invitegroups');

module.exports = {
    InviteGroup
}


InviteGroup.findOneAndUpdate(
 {
   "_id":mongoose.Types.ObjectId("5ecc1c6af2a26b884f4272eb"), 
   "inviteGroup": {"$elemMatch":{"$elemMatch":{"biddingUserId":"4"}}}
 }, 
 {"$pull":{"inviteGroup.$":{"biddingUserId":"4"}}}, 
 {"new":true} ).exec((err, results) => {console.log("Results " +  JSON.stringify(results));}
)

输出

{
  "inviteGroup":[
    [
      {"biddingUserId":"3","username":"name3"},
      {"biddingUserId":"2","username":"name2"}
    ],
    [ {"biddingUserId":"1","username":"name1"}
    ]
  ],
"_id":"5ecc1c6af2a26b884f4272eb"
}

答案 1 :(得分:1)

var ObjectId = mongoose.Types.ObjectId;
   Post.findByIdAndUpdate(
      { _id: req.params.id },
      {
        $pull: { inviteGroup: {biddingUserId : ObjectId(req.body.userInvited.biddingUserId) }}
      },
      function (err, docs) {
        if (err) {
          console.log("err$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
          console.log(err);

          context.res = {

            status: 500,

            body: {
              message: "Add Invite Error!",
              error: err

            },

            headers: {
              "Access-Control-Allow-Credentials": "true",
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Methods": "PATCH, OPTIONS",
              "Access-Control-Allow-Headers": "Content-Type, Set-Cookie",
              "Access-Control-Max-Age": "86400",
              "Vary": "Accept-Encoding, Origin",
              "Content-Type": "application/json"
            }

          };

          context.done();



        } else {
          context.res = {

            status: 200,

            body: {
              message: "User Invited Successfully!",
              error: err

            },

            headers: {
              "Access-Control-Allow-Credentials": "true",
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Methods": "PATCH, OPTIONS",
              "Access-Control-Allow-Headers": "Content-Type, Set-Cookie",
              "Access-Control-Max-Age": "86400",
              "Vary": "Accept-Encoding, Origin",
              "Content-Type": "application/json"
            }

          };

          context.done();

        }
      });

答案 2 :(得分:1)

这是一个可行的解决方案

var mongoose = require('mongoose');
const { Schema, Types: { ObjectId } } = mongoose;

mongoose.connect('mongodb://localhost/test', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false 
})

const PostSchema = new Schema({
    inviteGroup: [{
        biddingUserId: { type: String, lowercase: true, trim: true },
        username: { type: String, lowercase: true, trim: true }
    }],
});
const Post = mongoose.model('Posts', PostSchema)

//Example data
var post1 = new Post({
    _id: ObjectId('5ecbf32fba4c9d4c34ea829b'),
    inviteGroup: [
        { biddingUserId: '5ecbfec14cc7af2bf043134f', username: 'bob1' },
        { biddingUserId: '5ecbfec14cc7af2bf0431351', username: 'bob2' },
        { biddingUserId: '5ecbfe0102aa1921bcee9092', username: 'bob3' },
    ]
});
var post2 = new Post({
    _id: ObjectId('5ecbf32fba4c9d4c34ea829e'),
    inviteGroup: [
        { biddingUserId: '5ecbfc3663dfea3ccc5e6b5e', username: 'joe1' },
        { biddingUserId: '5ecbfc3663dfea3ccc5e6b5f', username: 'joe2' },
        { biddingUserId: '5ecbfc3663dfea3ccc5e6b5d', username: 'joe3' },
    ]
});


Post.create([post1, post2]).then(docs => {
    //The docs are now saved to MongoDB.
    console.log('Number of docs => ' + docs[0].inviteGroup.length);// length = 3
    //Let's delete username=bob2 whose biddingUserId=5ecbfec14cc7af2bf0431351 from the first document
    return Post.findByIdAndUpdate(
        { _id: '5ecbf32fba4c9d4c34ea829b' },
        { $pull: { inviteGroup: { biddingUserId: '5ecbfec14cc7af2bf0431351' } } }
    )
}).then(doc=> {
    //Let's verify that the user is removed
    return Post.findById(doc._id)
}).then(doc=> {
    console.log(doc.inviteGroup); // Contains only two users (bob1 and bob3)
    console.log('Number of docs => ' + doc.inviteGroup.length);// length = 2
}).catch(err => {
    console.log(err.message)
})

注意:如果您正在使用MongoDB指南针(例如)验证从MongoDB中删除了该文档, 别忘了刷新收藏集