更新嵌入式文档不工作mongoose

时间:2014-10-21 18:09:48

标签: node.js mongodb mongoose

该集合包含以下条目

> db.tags.find()
{ "_id" : ObjectId("5446a012cdc70d0732565c84"), "tag" : "java", "data" : [ { "date" : "2001/1/20", "view" : "700" } ], "__v" : 0 }

当我尝试使用以下代码将数据推送到数组时

var Tag =  require('./DBConn');
var condtion = {"_id" : "5446a012cdc70d0732565c84"}
var updateData ={  
           "data":[  
              {  
                   "date":"2001/1/21",
                   "view":"145"

              }
           ]

}
tag.update(condtion,{$push:updateData},function (err) {
  if (!err) console.log('Update Success!');

});

并查询集合,它提供相同的记录,而不更新集合,

> db.tags.find()
{ "_id" : ObjectId("5446a012cdc70d0732565c84"), "tag" : "java", "data" : [ { "date" : "2001/1/20", "view" : "700" } ], "__v" : 0 }

我在更新中做了什么错,在哪里纠正这个?

添加了完整的代码

ModelT.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/stack1');


var stackSchema = mongoose.Schema({
    name: String
})

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var tagData = new Schema(
{
    tag  : String,
    data :[viewData]
}
    )
var viewData = new Schema({
    view     : String,
    date      : Date
});

module.exports = mongoose.model('Tag', tagData);

Test.js文件

   var Tag =  require('./ModelT');
var condtion = {"_id" : "5446acd5277da1896bb326a6"}
var updateData = {
          "data": {  
            "date":"2001/1/21",
            "view":"145"
          }
        };

//var updateData = {
//        "data": { $each: [{
//          "date":"2001/1/21",
//          "view":"145"
//        }]}
//      };
var tag = new Tag(

);
Tag.update(condtion,{$push:updateData},function (err) {
  if (!err) console.log('Update Success!');

});

1 个答案:

答案 0 :(得分:2)

将值数组传递给$push运算符时,需要使用$each修饰符:

var updateData = {
  "data": { $each: [{
    "date":"2001/1/21",
    "view":"145"
  }]}
};

或者只是传递单个对象而不将它放在数组中:

var updateData = {
  "data": {  
    "date":"2001/1/21",
    "view":"145"
  }
};

tag.update(condtion, {$push: updateData}, function (err) {
  if (!err) console.log('Update Success!');
});