快递' res.render'错误:多次渲染页面

时间:2015-01-16 17:57:08

标签: node.js mongodb express mongoose

我正在使用一个简单的查询来查找数据库中的值,因为我返回到一个页面,它使用检索到的对象正确呈现页面,然后使用null对象再次呈现它(没有找到) ,并且console.log文件正在运行两次,一次使用正确的数据,一次没有任何内容。这是快递的问题吗?

 app.get('/user/:userid',isLoggedIn, function(req, res){
        var newmodel;
        mongoose.model('studentusers').find({ "userid" : req.params.userid }, function(err, docs){ //search for specific object that matches parameters
             console.log("DOCS: " + docs); //Check to see if the query worked
             //Here I just do some formatting on the object to be able to 
             var model = docs;
             model = JSON.stringify(model);
             model = model.replace("[", "");
             model = model.replace("]", "");
             console.log("model: " + model);//check to see if model is correct
             newmodel = JSON.parse(model);

            //The res.render returns the page once with the 'DOCS:' and 'model:' console.log files outputting the json info, and then again with nothing afterwards
             res.render('user.ejs',
                {
                    student: newmodel,
                });        
        });         
    });

然后,当我看到'DOCS:'和'model:'的正确输出后,它再次显示'DOCS:'和'model:',除了空,我收到此错误:

undefined:0

^
SyntaxError: Unexpected end of input
at Object.parse (native)
at Promise.<anonymous> 

1 个答案:

答案 0 :(得分:0)

您不需要具有将docs对象转换为newmodel对象的任何代码。这是无关紧要的,因为find返回一个数组。如果你转换mongoose调用以使用findOne方法,你应该只能这样做:

app.get('/user/:userid',isLoggedIn, function(req, res){
    mongoose.model('studentusers').findOne({userid: req.params.userid }, function(err, user){ 
        res.render('user.ejs', {student: user});        
    });         
});