2017-02-28 61 views
0

车型的特性 '支数'/ 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; 

型号/ 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); 
    }); 
    }); 
}); 

我得到以下错误:

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)

回答

0

index.js你没有在任何地方包括你的模型。 Theres没有办法让猫鼬知道这些模型存在,除非您将模型文件包含在某处,以便在猫鼬对象中填充模型。

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'); 
+0

不过现在面临同样的问题。 – user3214361

相关问题