从数组中删除特定对象-Node.js

时间:2019-07-25 07:52:45

标签: javascript node.js mongodb mongoose

我是Node.js的新手。 我有一些这样的数据

enter image description here

我想更新此歌曲对象并删除歌手“ hanna” ..以便最终使歌曲中没有歌手。

我尝试了很多方法,其中一些在这里被评论

这是我的代码:

var data = req.body;

  let songCondition = {
    "artist.$.id": data._id,
  }
  let updateSong = {
    // $pull: { "artist": { "id": data._id } }
    // $pull: { "artist": { "id": { $in: [data._id] } } }
    $pull: { artist: { $elemMatch: { id: data._id } } }
  }

  let updateSongData = await Query.findAndUpdate(Song, songCondition, updateSong);

有人可以建议我在这里做错什么吗?

1 个答案:

答案 0 :(得分:2)

findOneAndUpdate函数中,第一个参数用于filter,第二个参数用于update

const { _id } = req.body

Song.findAndUpdate(
  { "songs.artist": { "$elemMatch": { id: _id }}}, // first parameter is for fitler
  { "$pull": { "artist": { "id": _id } } } // second one for update
)