【问题标题】:Delete specific object from array - Node.js [duplicate]从数组中删除特定对象-Node.js [重复]
【发布时间】:2019-12-03 10:24:34
【问题描述】:

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

我想更新这个歌曲对象并删除艺术家“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);

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    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
    )
    

    【讨论】:

    • 谢谢你,你救了一天:)
    猜你喜欢
    • 2012-11-25
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 2017-04-10
    • 1970-01-01
    相关资源
    最近更新 更多