2016-06-25 64 views
0

應對編號在我的node.js的代碼,當我追加的客戶有一個ID我的車,但追加這樣MongoDB的node.js中沒有的ObjectId

"customer" : ObjectId("5755251e4e2210ce2f953407") 有沒有辦法讓這樣的

"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 
     }); 
    }); 
} 

回答

0

只需添加的ToString()如下:

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 
     }); 
    }); 
}