我为每个拥有node和mongoose的用户创建了一个动态模式,如下所示。
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
require('mongoose-currency').loadType(mongoose);
var Currency = mongoose.Types.Currency;
var values = 'Credit Debit'.split(' ');
var schema = new Schema({
amount: {
type: Currency,
required: true
},
type: {
type: String,
enum: values
},
description: {
type: String,
required: true
}
},
{
timestamps: true
});
exports.create_database = function(mobile) {
return mongoose.model('personal_'+mobile, schema, 'personal_'+mobile);
};
我在下面给出的个人路由器代码中使用了这个
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var database = require('../models/personal');
var Verify = require('./verify');
var personalRouter = express.Router();
personalRouter.use(bodyParser.json());
personalRouter.route('/')
.get(Verify.verifyOrdinaryUser, function (req, res, next) {
var mobile = req.decoded._doc.mobile;
var Personal = database.create_database(mobile);
Personal.find(req.query)
.exec(function (err, personal) {
if (err) next(err);
res.json(personal);
})
})
.post(Verify.verifyOrdinaryUser, function(req, res, next) {
var mobile = req.decoded._doc.mobile;
var Personal = database.create_database(mobile);
Personal.create(req.body, function(err, personal) {
if(err) next(err);
console.log('Personal Record added!');
var type = personal.type;
var amount = personal.amount/100;
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Added the '+type+' record of amount = '+amount);
})
})
module.exports = personalRouter;
现在一切都运行良好的get和post路由器,直到我传递的值不是mongoose模式。 例如。如果我在没有描述的情况下传递值,我的服务器将给出验证错误并崩溃。 我尝试用throw替换下一个(错误)(错误的代码没有任何运气。 我希望显示错误并防止服务器崩溃和关闭。 请帮助我,我哪里出错?