MongoDB在完全重启之前不会更新(Node JS)

时间:2018-08-06 18:18:43

标签: javascript arrays node.js mongodb request

我一直试图在我的网站中添加搜索功能。这将允许用户查找彩带。我直接从twitch API获取流光,并一直在使用MongoDB来存储用户。我遇到的问题是没有将拖缆放入拖缆数组中。即使当我刷新页面时,拖缆仍未放入数组中。仅在我搜索其他流媒体或完全重新启动站点时添加。

router.get("/search", function(req, res){
// Get search value
var search = req.query.search.toLowerCase();
// find streamer with search variable
function findStreamer(streamers){
    return streamers["name"].toLowerCase() === search;
}
var foundStreamer = streamers.find(findStreamer);

//check if user is found
if((foundStreamer === undefined) || (foundStreamer === null)){
    //if user is not found, add user to database
    console.log("Streamer not found. Adding streamer to database")
    getStreamerByName(search, function(){

        //update the streamers in the streamers array
        Streamer.find({}, function(err, allStreamers){
            streamers = Array.from(allStreamers)

            //find streamer
            function findStreamer(streamers){
                return streamers["name"].toLowerCase() === search;
            }
            var foundStreamer = streamers.find(findStreamer);

            //check what streamers are in the array
            streamers.forEach(function(streamer){
                console.log(streamer.name)
            })

            //if the the user is found
            if((foundStreamer === undefined) || (foundStreamer === null)){
                res.redirect("/streamers");
            }
            //else
            else{
                res.render("streamers/show", {streamer: foundStreamer});
            }
        });

    });
}
else{
    // display streamer data
    res.render("streamers/show", {streamer: foundStreamer});
}

});

1 个答案:

答案 0 :(得分:0)

经过数小时的尝试不同的事情并在各处进行研究之后,我终于找到了解决方案。不幸的是,我所做的任何研究都没有提供帮助,只是通过反复试验来解决问题。如果有人遇到相同的问题,这是更新的代码。

router.post("/search", function(req, res){
// Get search value
var search = req.body.search.toLowerCase();

// find streamer with search variable
function findStreamer(streamers){
    return streamers["name"].toLowerCase() === search;
}
var foundStreamer = streamers.find(findStreamer);

//check if user is found
if((foundStreamer === undefined) || (foundStreamer === null)){
    //if user is not found, add user to database
    getStreamerByName(search, function(streamer){
        Streamer.create(streamer, function(err, streamer){
            //update the streamers in the streamers array
            Streamer.find({}, function(err, allStreamers){
                streamers = Array.from(allStreamers)
            });
            res.render("streamers/show", {streamer: streamer});
        });
    });
}
else{
    // display streamer data
    res.render("streamers/show", {streamer: foundStreamer});
}
});