我正在使用express和mongoose将我的表单数据保存到mongodb数据库中,但操作无法正常工作,因为它会给我一个错误,即我的模型未注册。我的代码:
index.ejs
<!DOCTYPE html>
<html>
<head>
<title>Admin-Page</title>
</head>
<body>
<h1>admin-dashboard-interest</h1>
<form method="post" action="">
<label for="select1">min select:</label>
<select name="interest_active_user_min" id="select1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<label for="select2">max select:</label>
<select name="interest_active_user_max" id="select2">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit">
</form>
</body>
</html>
schema.js
var InterestSchema = new Schema({
settings: {
admin_settings: {
interest_settings: {
interest_pending_user_settings: {
type: Number,
max: 100,
default: 0
},
interest_pending_user_value: {
type:[String]
},
interest_active_user:{
type:Number,
max:1000,
default:0
},
interest_active_user_max: {
type: Number,
max:1000,
default:100
},
interest_active_user_min: {
type: Number,
max:1000,
default: 5
},
active_interest: [{
name: {
type:[String],
unique:true
},
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
timestamp: {
type:Date,
default: Date.now
}
}],
pending_interest: [{
name: {
type:[String],
unique:true
},
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
timestamp: {
type:Date,
default: Date.now
}
}],
declined_interest: [{
name: {
type:[String],
unique:true
},
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
timestamp: {
type:Date,
default:Date.now
}
}],
removed_interest: [{
name: {
type:[String],
unique:true
},
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
timestamp: {
type:Date,
default: Date.now
}
}]
}
}
}
});
var Int = mongoose.model('Interest', InterestSchema);
server.js
var mongoose = require('mongoose');
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var morgan = require('morgan');
var bodyParser = require('body-parser');
var uri = 'mongodb://localhost/interest';
var db = require('mongoose').connect(uri);
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.set('view engine', 'ejs');
app.listen(port);
console.log('shit happens on port ' + port);
app.get('/', function(req,res){
res.render('index.ejs');
});
app.post('/', function(req,res){
var content = new Int(req.body.content);
content.save(function(err){
if(err){
return handleError(err);
} else {
console.log('your form has been saved');
}
})
});
require('./models/schema.js');
我得到一个错误“Int is not defined”,这是我用来注册mongoose模型的变量。我还要求在我的server.js中有mongoose文件,这样我就看不出哪里出错了。
3条答案
按热度按时间pftdvrlh1#
在schema.js中替换
并在server.js中添加
现在可以了。
在
schema.js
中添加var mongoose = require('mongoose');
并且架构应该匹配。
uplii1fm2#
在schema.js中,将最后一行更改为
和server.js中(删除最后一行)
ct2axkht3#
html表单中的操作为空add action="/”