express.js中的console.log不记录mongodb ._id字段

时间:2017-11-14 17:54:31

标签: javascript mongodb express

我有一个奇怪的情况,我无法弄清楚原因。 我学习了MEAN并进行了以下设置:

我的PUG文件:

    br
  for product in products
    div.container
      div.row.border
        div.col-md-3
          p= product.name
          p= product._id
        div.col-md-3
          p= product.description
        div.col-md-3
          p= "$" + " " +product.price
        div.col-md-3
          form(action="/cart", method="post")
            input(type="hidden", value="#{product._id}" , name="id")
            button(type="Submit") Add To Cart

我的index.js文件(基本只显示我的文档并删除它们)

    var express = require('express');
var router = express.Router();
var cart = require('../lib/Cart.js');
var db = require('../lib/db.js');
var database = require('../database.js')

var mongoose = require('mongoose');
var Products = mongoose.model('Product');
var User = mongoose.model('User');

mongoose.connect = ('mongodb://localhost/products');


/* GET home page. */
router.get('/', function (req, res) {
    // console.log(sayHelloEnglish());

    Products.find(function (err, products) {
        res.render('index', { title: 'Express 2017 ', products: products });
        console.log(products);
    });
});


router.post('/', function (req, res) {
   // var newUser = new User ({name : req.body.name});
   // newUser.save(function(err, users){
     //   res.render('index', {title: "whatever"})
    //});

     var newProduct = new Products({ name: req.body.name, description: req.body.description, price: req.body.price });
    newProduct.save(function (err, products) {
        res.render('index', { title: "PRODUCTS", products: products });
    });
});

 //console.log is logging #{product._id} and not the value???
router.post('/cart', (function (req, res) {
    var id = req.body.id
    console.log(id);
    res.render('cart', {title: "Cart"});
}));

module.exports = router;

以下是问题: 我的console.log结果是

#{product._id}

它没有记录实际ID,如下所示:5a0341e2ff549f2de8e307be 任何见解都会受到高度赞赏,因为我无法弄明白。 为什么console.log显示@ {product._id}而不是实际的id值?

1 个答案:

答案 0 :(得分:1)

pug中不再支持这种属性:

 input(type="hidden", value="#{product._id}" , name="id")

改为使用:

 input(type="hidden", value=product._id , name="id")

此处的迁移指南中有更多示例:https://pugjs.org/api/migration-v2.html#attribute-interpolation