如何使用mongoose从数组中删除元素

问题描述 投票:0回答:1

我有点卡住了。我正在尝试使用mongoose从数组中删除元素。我用了 :

my_collection.update({
    user: req.query.user
}, {
    $pullAll: { //or $pull
        my_array: array[index] //= "elem1"
    }
});

不幸的是它真的不起作用......

这是我的文件,如果它可以帮助:

{
 "_id":"5a997cde9872f41085391f51",
 "my_array":
     ["elem1",
      "elem2",
      "elem3",
      "elem4"],
 "user":"rodolphe",
 "__v":0
}

谢谢您的帮助!

node.js database mongodb express mongoose
1个回答
0
投票

请参阅$pullAll,它需要一个数组参数,您传递了一个字符串。

这是我运行代码时遇到的错误:MongoError: $pullAll requires an array argument but was given a string

确保使用.catch()控制您的错误。

// mock data
const req = { query: { user: "rodolphe" } }
const array = ["elem1"];
const index = 0;

// update record
Collection.update({
  user: req.query.user
}, {
  $pullAll: { //or $pull
      my_array: [array[index]] // WRAP WITH AN ARRAY
  }
})
  .then(res => console.log(res))
  .catch(err => console.log(err));
© www.soinside.com 2019 - 2024. All rights reserved.