更新模型中的模型

时间:2017-04-24 13:58:19

标签: node.js mongodb mongoose

A & D topical
A + D Cracked Skin Relief cream
A-200 Lice Treatment....
.............

我有一个名为"用户"的模型。这个JSON是用户之一。 好的,所以"三"中的对象他们自己的模型称为" Time"。我想通过他们的id选择其中一个,然后更新它。我怎么能这样做?我正在使用猫鼬。显然,Time.findOne()不起作用,因为该集合是"用户" 包含"时间"。

{
    "_id": "58fa4b4fa377ac2840cd1478",
    "password": "pass",
    "username": "test",
    "__v": 45,
    "stats": {
        "three": [
            {
                "_id": "58fceef81e862e16f0501c1c",
                "time": 115,
                "scramble": "L2 R' U' L2 F2 B R' U' B2 L F' B' D B' F' D U B",
                "status": 0,
                "date": "2017-04-23T18:14:16.412Z"
            },
            {
                "_id": "58fceefd1e862e16f0501c1d",
                "time": 135,
                "scramble": "D F L2 U2 R2 B2 F2 R B D' R' F' B L U2 F' U2 F U' F",
                "status": 0,
                "date": "2017-04-23T18:14:21.434Z"
            },
            {
                "_id": "58fcef031e862e16f0501c1e",
                "time": 101,
                "scramble": "R' F R B R' L2 B' U2 D R2 F L U R2 B2 D' F U R' D",
                "status": 0,
                "date": "2017-04-23T18:14:27.572Z"
            },
            {
                "_id": "58fdc8311e862e16f0501c1f",
                "time": 87,
                "scramble": "L2 F B' F D' B2 L2 U B2 D U2 L B' F2 B2 F2 D' R",
                "status": 0,
                "date": "2017-04-24T09:41:05.334Z"
            }
        ]
    },
    "accountDate": "2017-04-21T18:11:27.946Z"
};

1 个答案:

答案 0 :(得分:0)

代码未编译..

 yourUserModel.findById(userId, function(err,user) {  
          var i;
            if(err || user === null){
            return;
            }
           var stats = user.stats;

           for(i =0; i<stats.three.three.length; i=i+1) {
              if(stats.three[i]._id === yourId) { //id of object to be updated
                  stats.three[i].status = 1; //updating
    }

    }
user.stats = stats;
user.save();
            });