mongodb node.js coping Id without ObjectId

514 Views Asked by At

In my node.js code when I'm appending customer with an Id to my cart, but it is appending like this

"customer" : ObjectId("5755251e4e2210ce2f953407") is there a way to get like this

"customer" : "5755251e4e2210ce2f953407"


function login(req, res, next) {
    db.users.findOne({
            'email': req.body.email
        }, function(err, user) {
            if (err) return next(err);
            if (!user) {
                return res.status(401).send("user not found");
            }
            if (lib.getSaltedPassword(req.body.password) != user.password) {
                return res.status(401).send("wrong password");
            }
            req.session.user = user;
            if (req.session.cart) {
                req.session.cart.forEach(function(data) {
                    data.customer = user._id
                })
                db.carts.insert(req.session.cart, function(err, user_cart) {
                    if (err) return next(err);
                })
            }
        }
         res.send({
            message: 'logged in',
            user_id: user._id
        });
    });
}
1

There are 1 best solutions below

0
Abdul Rehman Sayed On

simply add a .toString() as follows :

function login(req, res, next) {
    db.users.findOne({
            'email': req.body.email
        }, function(err, user) {
            if (err) return next(err);
            if (!user) {
                return res.status(401).send("user not found");
            }
            if (lib.getSaltedPassword(req.body.password) != user.password) {
                return res.status(401).send("wrong password");
            }
            req.session.user = user;
            if (req.session.cart) {
                req.session.cart.forEach(function(data) {
                    data.customer = user._id.toString();
                })
                db.carts.insert(req.session.cart, function(err, user_cart) {
                    if (err) return next(err);
                })
            }
        }
         res.send({
            message: 'logged in',
            user_id: user._id
        });
    });
}