0
votes

models / branch.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var branchSchema = new Schema({
  merchant_id: { type: [String], index: true },
  contact_name: String,
  branch: String,
  phone: String,
  email: String,
  address: String,
  status: String,
  created_date: { type: Date, default: Date.now },
  merchants: [{ type: Schema.Types.ObjectId, ref: 'merchant' }]

});
var branch = mongoose.model('branch', branchSchema);
exports = branch;

models / merchants.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var merchantSchema = new Schema({
  merchant_name: String,
  merchant_type: String,
  contact_name: String,
  phone: String,
  email: String,
  Address: String,
  created_date: { type: Date, default: Date.now },
  branches: [{ type: Schema.Types.ObjectId, ref: 'branch' }]
});
var merchant = mongoose.model('merchant', merchantSchema);
exports = merchant;

index.js

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var merchant = mongoose.model('merchant');
var branch = mongoose.model('branch');

router.post('/merchants/:merid/branch', function(req, res, next) {
  var branchs = new branch(req.body);
  branch.post = req.post;
  branchs.save(function(err, post) {
    if (err) {
      return next(err);
    }
    req.post.branch.push(merchant);
    req.post.save(function(err, post) {
      if (err) {
        return next(err);
      }
      res.json(branch);
    });
  });
});

I am getting following error:

TypeError: Cannot read property 'branchs' of undefined at C:\survey-system\routes\index.js:80:14 at C:\survey-system\node_modules\mongoose\lib\model.js:3431:16 at C:\survey-system\node_modules\mongoose\lib\services\model\applyHooks.js:144:20 at _combinedTickCallback (internal/process/next_tick.js:67:7) at process._tickCallback (internal/process/next_tick.js:98:9)

1

1 Answers

0
votes

In index.js you aren't including your models anywhere. Theres no way for mongoose to know those models exist unless you include the model files somewhere to populate the model in the mongoose object.

index.js

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var models = require('./models.js'); //This calls the js file models which then run their code, adding the models to mongoose.

//Now accessible.
var merchant = mongoose.model('merchant');
var branch = mongoose.model('branch');
...

models.js

var merchants = require('./models/merchant.js');
var branch = require('./models/branch.js');