【问题标题】:Inserting an object into a list on a mongoDB collection将对象插入到 mongoDB 集合的列表中
【发布时间】:2020-11-08 12:14:48
【问题描述】:

我有一个使用以下架构创建的集合

const userSchema = new mongoose.Schema({
    Name: String,
    email: String,
    music: Array
});


var User = new mongoose.model("User", userSchema);

但是,我在将下面的对象插入音乐数组时遇到问题

  var newMusic = {
      artist: "Rihanna",
      title: "Believe It"
    };

下面是我正在运行的将上述内容插入音乐数组的代码

 User.update({
      _id: req.user._id
    }, {
      $push: {
        music: newMusic
      }
    });

没有错误信息,只是没有更新文档。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    我终于明白了。以下代码有效

    User.update({
          _id: req.user._id
        }, {
          $push: {
            music: newMusic
          }
        }).then(data => {
          console.log(data);
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 2011-06-02
      • 2020-07-16
      • 2016-09-22
      相关资源
      最近更新 更多