【问题标题】:push an element to an array in a mongoose document将元素推送到 mongoose 文档中的数组
【发布时间】:2014-10-01 05:33:40
【问题描述】:

我的架构如下:

var schema = new mongoose.Schema({
_id: String,
name:String,
to:[{
   name: String,
   message: [{
      content: String
      timestamp: Date
            }]
   }]
});

我需要将{content: Content, timeStamp: timestamp} 推送到message 数组,其中to.name == "someName"。

我尝试过这种方式但无法成功。请帮助我。

User
  .find({_id: id})
  .where('to.name').equals("someName")
  .to.message.push({content: Content, timeStamp: timestamp})
  .exec(function(err, doc){
            if(err) return console.log(err);
            console.log(doc);
        });

【问题讨论】:

    标签: mongoose chat database-schema


    【解决方案1】:

    您可以通过使用$push 运算符的update 来做到这一点:

    User.update(
      {_id: id, 'to.name': 'someName'},
      {$push: {'to.$.message': {content: Content, timeStamp: timestamp}}},
      function(err, numAffected) { ... }
    );
    

    位置$运算符用于引用查询匹配的to元素的索引。

    【讨论】:

      猜你喜欢
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2014-05-28
      • 2015-05-11
      • 2018-04-12
      • 1970-01-01
      相关资源
      最近更新 更多