将元素推送到mongoose文档中的数组

时间:2014-10-01 05:33:41

标签: mongoose chat database-schema

我的架构如下:

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);
        });

1 个答案:

答案 0 :(得分:1)

您可以使用update运算符的$push执行此操作:

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

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