Home > Software engineering >  EJS template engine node js express and mongoose not working properly
EJS template engine node js express and mongoose not working properly

Time:11-03

I'm a beginner student of node js and i'm developing a simple inventory app. In my code, I'm currently using the MVC architecture, EJS as the template engine and MongoDB as the data base.

When I try to iterate over the resulting .find({}) method array in the EJS file, it seems like I get an empty array and no errors.

Basically, this is what I've tried:

MODEL:

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

productInstanceSchema = new Schema({
    product:{type: Schema.Types.ObjectId,ref: "RawProduct"},
    date_added: {type: Date,required:true},
    price:{type: Number, required:true},
    expiration_date: {type:Date}
});

productInstanceSchema.virtual("url").get(function () {
    return `product/productinstance/${this._id}`;
  });
  
  module.exports = mongoose.model("ProductInstance", productInstanceSchema);

CONTROLLER:

const RawProduct =  require('../models/raw_product');
const ProductInstance = require('../models/productinstance');

exports.productinstances_byproduct = function (req,res,next) {
        ProductInstance.find({})
        .populate("product")
        .exec(function (err, product_instances) {
            if (err){
                return next(err);
            };
            res.render('inventory', {instances:product_instances})
        })
}

VIEW (.ejs file):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>ESTOQUE</h1>
        <ul>
            <% instances.forEach(function(instance) { %>
                <li>
                    product: <%= instance.product %>
                </li>
            <% }); %>
                
        </ul>
</body>
</html>

when I execute the route, I get an empty result: Error

Can you guys please help me find what is wrong with my code?

EDIT: as suggested, I've made a test Script to log the results of the .find() method in the console and this is the result:

[
  {
    _id: new ObjectId("63399c7664a90dd9edc43c58"),
    product: {
      _id: new ObjectId("63399c7664a90dd9edc43c56"),
      name: 'Batata-Frita',
      description: 'BATATA PRÉ-FRITA TRADICIONAL CONGELADA MCCAIN PACOTE 1,5KG',
      category: new ObjectId("63399c7664a90dd9edc43c54"),
      EAN: '7797906000892',
      unit: 'kg',
      brand: 'McCain',
      ideal_ammount: 5,
      __v: 0
    },
    date_added: 2022-10-02T14:13:10.239Z,
    price: 14.99,
    expiration_date: 2022-10-15T00:00:00.000Z,
    __v: 0
  }
]

And, briefly, here is how I add data to the product instance:

function productInstanceCreate(product, date_added, price, expiration_date, cb) {
  var productinstance = new ProductInstance({ 
    product: product,
    date_added: date_added,
    price: price,
    expiration_date: expiration_date
  });    
  productinstance.save(function (err) {
    if (err) {
      cb(err, null)
      return
    }
    console.log('New Product Instace: '   productinstance);
    productinstances.push(productinstance)
    cb(null, productinstance)
  } );
};

function createProductInstance(cb) {
    async.series([
        function(callback) {
          productInstanceCreate(rawproducts[0],new Date, 14.99,'2022-10-15', callback);
        },
    ], cb);
};

I use async series to control the flow and make shure categories and raw products are created before product instance

CodePudding user response:

I know this is rare...., Make sure the ObjectID saved there from the RawProduct. Let me know if they are. that was my case.

mongoose will check ObjectId of the product field and will search in the RawProduct collection.

can you check your database and post it?

I suggest reading the docs: Population

  • Related