【问题标题】:how to resolve error in sub documents mongoose/express如何解决子文档猫鼬/快递中的错误
【发布时间】:2014-07-19 05:44:01
【问题描述】:

我正在开发一个基于 Mean Stack 的 Web 应用程序,但我很关心添加和编辑操作,特别是对于字段“订单”的子文档,控制台告诉我“引用”未定义就行“order.reference”:req.body.order.reference, ,我不知道如何处理子文档。当我添加或修改任何“订单”字段时,我得到了一个错误,但是当我毫无例外地添加所有字段时它可以工作。这是我的猫鼬图:

var mongoose = require('mongoose')
, Schema = mongoose.Schema;

var ContactSchema = new Schema({
  name: {type: String},
  order: {
    reference : {type : String},
    adresse : {type : String} ,
    product : {type : String}
  }
});

var ContactModel = mongoose.model('Contact', ContactSchema); 
mongoose.connect('mongodb://localhost/contact');

exports.add = function(req, res) {
    var contact = req.body;
    contact = new ContactModel({
      name: req.body.name,      
      "order.reference" : req.body.order.reference,
      "order.adresse" : req.body.order.adresse,
      "order.product" : req.body.order.product
    });

    contact.save(function (err) {
      if (!err) {
        res.json(true);
      } else {
        console.log(err);
        res.json(false);
      }
    });
    return res.jsonp(req.body);
};

exports.edit = function (req, res) {
  var id = req.params.id;
  if (id) {
    ContactModel.findById(id, { upsert: true }, function (err, contact) {

      contact.name = req.body.name,
      contact.order.reference = req.body.order.reference,
      contact.order.adresse = req.body.order.adresse ,
      contact.order.product = req.body.order.product   

      contact.save(function (err) {
        if (!err) {
          res.json(true);
        } else {
          res.json(false);
          console.log(err);
        }
      });

    });
  }
};

谢谢你的时间,我可以提供角度代码和html

【问题讨论】:

    标签: express mongoose mean-stack


    【解决方案1】:

    您可能希望使用 Express 和正文解析器: How do you extract POST data in Node.js?

    注意:我相信这是为 Express 3 编写的,而 Express 4 的语法略有不同

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多