简体   繁体   中英

Pushing data into an array model in mongoose

Well, i have a conceptual problem and a real error... i'm working on an inventory module concept, is simple, it consist on two models:

  • Inventory
  • Item

The Inventory model just contains a "items" field, and that field is just a reference (to populete) to the real item object models, you know items: [type: String, ref: 'Item'] .

The Item object is the real data container, it have all data (name, itemCode, description, disponibility, existence... and so on). The problem in the concept is confusing for me.

When an item is created, it need to be pushed into the array "items" of Inventory model document, i coded this snippet, but it retrieve me an error:

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

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

My concept is really simple, and i tested the requires and exports of models, all looks fine, so, anyone have some idea to solution the problem?

Error:

Can't set headers after they are sent.

Error comes when you are sending the name of the field in schema and in api file wrong or in your HTML page and req.body parameter names incorrect.
Another way can be try using:

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

in your server.js file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM