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);
});
});
});
我收到以下错误:
TypeError:无法读取未定义的属性“分支” 在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 at _combinedTickCallback(internal / process / next_tick.js:67:7) at process._tickCallback(internal / process / next_tick.js:98:9)
答案 0 :(得分:0)
在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');