为什么在NodeJS中返回[object Object]

zvms9eto  于 2023-03-08  发布在  Node.js
关注(0)|答案(2)|浏览(447)

我目前正在管理员端添加一个新产品,然后我想在console.log中显示用户执行的操作,但它返回[object Object],我的代码目前有问题,有人能帮我解决这个问题吗?

exports.postFlower = (req,res,next) => {

            const stock = new Stocks ({
                user: req.session.user._id,
                flowerName: req.body.flowerName,
                quantity: req.body.quantity 
            })
            stock.save((err, stock) => {
                if(stock){
                    console.log('Created flower for user: ' + req.session.user)
                    res.redirect('flowers-in-stock')
                }
            })
    
        }
Created flower for user: [object Object]

也许这能帮我解决问题

exports.postLoginForm = (req,res) => {
    //console.log(req.body);
    User.findOne({email:req.body.email}).exec((err, user) => {
        if(err) return res.status(400).json({ message: err })

        if(user){
            if(user.password==req.body.password && user.role === 'admin'){
                //console.log("Done Login");
                console.log('admin login')
                req.session.isAdmin = true;
                req.session.user = {user};
                
                console.log(user)
                res.send({"Success":"Success!"});
                
            }else if(user.password==req.body.password && user.role === 'assistant'){
                console.log('assistant login')

                req.session.isAdmin = true;
                req.session.user = {user};
                
                console.log(user)
                res.send({"Success":"Success!"});

            } else{
                res.send({"Success":"Password is incorrect. Please try again."});
            }
        }else{
            res.send({"Success":"The email is not registered. Please try again."});
        }
    });
};
p1tboqfb

p1tboqfb1#

req.session.user是一个对象,而您试图将其连接到字符串,这导致JS将该对象转换为字符串,结果是“[object Object]"。
像这样使用smth:

console.log(`Created flower for user: ${req.session.user.email}`);

或者这个:

console.log('Created flower for user: ', ${req.session.user});

或者甚至是这个:

console.log(`Created flower for user: ${JSON.stringify(req.session.user)}`);
gwbalxhn

gwbalxhn2#

因为您正尝试输出对象而不是用户。您可以将代码更改为

exports.postFlower = (req,res,next) => {

            const stock = new Stocks ({
                user: req.session.user._id,
                flowerName: req.body.flowerName,
                quantity: req.body.quantity 
            })
            stock.save((err, stock) => {
                if(stock){
                    console.log('Created flower for user: ' + req.session.user._id)
                    res.redirect('flowers-in-stock')
                }
            })
    
        }

记录用户的用户ID

相关问题