在添加之前将检查相同字段的mongoose更新

时间:2016-11-01 23:12:07

标签: node.js mongodb rest express crud

我已经解决了重复错误,这条路线会将剧集对象添加到剧集数组中,但我还没有解决如何检查查询不仅是文档ObjectId还是在剧集数组内部,并确保没有一个season_number和episode_number一起匹配我在req.body中添加的那个。

这是我的路线

router.put('/api/shows/:id/episodes/add', function(req, res){
    var setObject = req.body;
    setObject.episode_id = new mongoose.Types.ObjectId;
    Show.update({'_id':req.params.id}, {$push:{'episodes':setObject}}, function(err, doc){
        if(err){console.log(err)}
        else{res.json(doc)};
    })
})

这是我的数据库文件

{
    "_id" : ObjectId("58190ebffa6503f8d9e114cc"),
    "title" : "Designated Survivor",
    "poster" : "https://images-na.ssl-images-amazon.com/images/M/MV5BMTY5NzYzODU4N15BMl5BanBnXkFtZTgwNzA1MjUwMDI@._V1_.jpg",
    "rated" : "TV-14",
    "program_time" : 60,
    "network" : "ABC",
    "airs_on" : [
            "Wednesday"
    ],
    "streams_on" : [
            "123Movies",
            "Hulu Plus"
    ],
    "genre" : [
            "Drama"
    ],
    "users" : [ ],
    "episodes" : [
            {
                    "_id":ObjectId('#############'),
                    "season_number" : 1,
                    "episode_number" : 1,
                    "title" : "Pilot",
                    "watched" : true
            },
            {
                    "season_number" : 1,
                    "episode_number" : 2,
                    "title" : "The First Day",
                    "watched" : true
            },
            {
                    "season_number" : 1,
                    "episode_number" : 3,
                    "title" : "The Confession",
                    "watched" : true
            },
            {
                    "season_number" : 1,
                    "episode_number" : 4,
                    "title" : "The Enemy",
                    "watched" : true
            },
            {
                    "season_number" : 1,
                    "episode_number" : 5,
                    "title" : "The Mission",
                    "watched" : true
            },
            {
                    "season_number" : 1,
                    "episode_number" : 6,
                    "title" : "The Interrogation",
                    "watched" : false
            }
    ]
}

这是我在邮差中使用的电话

https://temp-crud-app-rawlejuglal.c9users.io/tv/api/shows/58190ebffa6503f8d9e114cc/episodes/add
-->body
   title 'The Traitor'
   watched false
   season_number 1
   episode_number 7

2 个答案:

答案 0 :(得分:0)

我认为您需要将第一个_id转换为ObjectId。 请参阅此 Convert string to ObjectID in MongoDB

答案 1 :(得分:0)

问题似乎是你的查询,它试图获取文档的方式,我建议在更新之前调用findOne,看看你是否真的得到了预期的文件,肯定你不能得到查询。

我也不确定'episode_number':{$gt:req.body.episode_number-1, $lt:req.body.episode_number+1}

背后的逻辑

为什么不能'episode_number': req.body.episode_number