TypeError:无法读取未定义的属性“分支”
Posted
技术标签:
【中文标题】TypeError:无法读取未定义的属性“分支”【英文标题】:TypeError: Cannot read property 'branchs' of undefined 【发布时间】:2017-07-19 19:12:25 【问题描述】:模型/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);
);
);
);
我收到以下错误:
在 C:\survey-system\routes\index.js:80:14 在 C:\survey-system\node_modules\mongoose\lib\model.js:3431:16 在 C:\survey-system\node_modules\mongoose\lib\services\model\applyHooks.js:144:20 在 _combinedTickCallback (内部/进程/next_tick.js:67:7) 在 process._tickCallback (internal/process/next_tick.js:98:9)
【问题讨论】:
【参考方案1】:在index.js
中,您没有在任何地方包含您的模型。除非您在某处包含模型文件以在 mongoose 对象中填充模型,否则 mongoose 无法知道这些模型的存在。
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');
【讨论】:
仍然面临同样的问题。以上是关于TypeError:无法读取未定义的属性“分支”的主要内容,如果未能解决你的问题,请参考以下文章
渲染中的错误:“TypeError:无法读取未定义的属性'_t'”在使用 Jest 的单元测试中
(节点:47028)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“表情符号”
NextJS:TypeError:无法读取未定义的属性“json”
TypeError:无法使用 TSLint 和 TypeScript 读取未定义的属性“getFullWidth”
[karma-server]:TypeError:无法读取未定义的属性“范围”-CI 环境中的 Angular 单元测试