2014-10-01 63 views
0

我的模式如下:推一个元素阵列的猫鼬文档中

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

可以与使用操作者$push一个update做到这一点:

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

的位置$操作者用于引用由查询相匹配的to元素的索引。