【问题标题】:Pushing data into an array model in mongoose将数据推送到猫鼬中的数组模型中
【发布时间】:2015-02-12 22:38:06
【问题描述】:

嗯,我有一个概念问题和一个真正的错误......我正在研究一个库存模块概念,很简单,它包含两个模型:

  • 库存
  • 项目

Inventory 模型只包含一个“items”字段,该字段只是对真实项目对象模型的引用(对 populete),您知道items: [type: String, ref: 'Item']

Item 对象是真正的数据容器,它包含所有数据(名称、itemCode、description、disponibility、existence... 等等)。这个概念的问题让我很困惑。

当一个项目被创建时,它需要被推入库存模型文档的数组“项目”中,我编写了这个sn-p,但它检索到一个错误:

var inventario = new Inventario(); //The inventory document instance

var inventarios = router.route('/inventarios');

inventarios.post(function(req, res) {
// itamdata object
var nuevoItem = {
    _id: req.body._id,
    descripcion: req.body.descripcion,
    costo: req.body.costo,
    precioMin: req.body.precioMin,
    precioMax: req.body.precioMax,
    existencia: req.body.existencia,
    disponible:req.body.disponible
  };
  // Create a new item
  Item.Create(nuevoItem, function(err, item) {
    if(err) {
      res.status(500).json({
        msg: 'Problema interno con la base de datos',
        error: err
      });
    }
    // call push from push method of documents array
    inventario.items.push({ _id: nuevoItem._id });

    res.status(200).json({msg: 'Item Creado', token: item});
  }); // fin Item.Create

}); //fin inventarios.post

错误是:/home/nano/Dev/JS/OMI/node_modules/express/lib/router/index.js:482 this.stack.push(layer); ^ TypeError: Cannot call method 'push' of undefined

我的概念很简单,我测试了模型的需求和导出,一切看起来都很好,那么,有人有解决问题的想法吗?

【问题讨论】:

  • 您的 Inventario() 构造函数看起来有问题。能否请您出示该代码。
  • @KiranPagar 我用一个更友好的结构重写了所有代码,错误得到了解决......现在我遇到了另一个奇怪的错误,有些像Error: Can't set headers after they are sent.
  • 这是很常见的错误,这里是很好的答案stackoverflow.com/questions/7042340/…

标签: javascript node.js mongodb mongoose


【解决方案1】:

错误:

发送后无法设置标题。

当您在架构和 api 文件中发送错误的字段名称或在您的 HTML 页面中和 req.body 参数名称不正确时,会出现错误。
另一种方法可以尝试使用:

app.use(bodyParser.json({limit: '5mb'})); 

在您的 server.js 文件中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-22
    • 2018-05-17
    • 2019-10-13
    • 2018-09-19
    • 1970-01-01
    • 2016-01-29
    • 2021-02-09
    • 1970-01-01
    相关资源
    最近更新 更多