无法在Node.Js中访问MongoDB文档的字段

时间:2020-01-12 23:46:00

标签: node.js mongodb express

我正在使用猫鼬并在我的nodejs项目上进行表达。 试图从这里获取数据

app.get('/offers/:id', (req, res) =>{

//store the id from the url
var id = req.params.id;

//just a placeholder
var data = {title: "title", description:"description"};


//store the returned object in a variable
var oop  = offers.findById(id, function (err, user) {
    if(err){

       return err;

    }else{

        title = user.title;

        description = user.description;

        this.obj = {
            title:title,
            description:description
        }


        console.log(obj)
        return obj;
    }
 } );

    console.log(oop)


 res.render('single', {data:data});

});

所以我的想法是从URL中获取帖子ID,在数据库中找到它,然后在ejs模板上的相应位置显示标题和说明,但是由于某些原因,我无法访问返回的数据,我得到的是一长串属于mongodb的对象,没有“ title”或“ description”

2 个答案:

答案 0 :(得分:0)

我刚刚修改了您的代码并添加了注释(全部以“ ***”开头)。

app.get('/offers/:id', (req, res) =>{

    //store the id from the url
    var id = req.params.id;

    //just a placeholder
    var data = {title: "title", description:"description"};


    //store the returned object in a variables
    // var oop  = ***no need for this, the data you want will be  in the user variable.
    offers.findById(id, function (err, user) {
        if(err){

            return err;

        }else{

            // ***this needs to be changed to...
            // title = user.title;
            // description = user.description;
            // ***that...
            data.title = user.title;
            data.description = user.description;

            // ***what's that for??
            // this.obj = {
                // title:title,
                // description:description
            // }


            // ***this needs to be inside mongoose's callback
            res.render('single', {data:data});
        }
    });  

});

答案 1 :(得分:0)

尝试一下,您的代码有两个问题,并且您还需要使用.lean()来获取原始的Js对象而不是mongoDB文档:

app.get('/offers/:id', (req, res) => {

    //store the id from the url
    var id = req.params.id;

    //just a placeholder
    var data = { title: "title", description: "description" };

    //store the returned object in a variable
    offers.findById(id).lean().exec((err, user) => {
        if (err) {
            console.log(err);
            res.send(err)
        } else {
            data.title = user.title;
            data.description = user.description;
            this.obj = {
                title: title,
                description: description
            }
            console.log(obj);
            res.render('single', { data: data });
            // (Or) res.render('single', { data: obj });
        }
    });
});