我有一个注册页面,它将输入用户名和密码存储到mongoDB中。
在终端中也会导致Mongoose错误,说MongooseError:在保存新的MongooseError之前,文档必须有_id
以下是代码。
//server.js file
var express = require('express');
var app = express();
var port = 8888;
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
/*Body parser*/
app.use(bodyParser.urlencoded({
extended: true
}));
/*Database connection - MongoDB*/
//Created from the command earlier. Ensure this is done on the first_db instance
var username = 'admin';
var password = '123456';
var dbHost = 'localhost';
var dbPort = '27017';
var database = 'first_db';
var url = 'mongodb://' + username + ':' + password + '@' + dbHost + ':' + dbPort + '/' + database;
console.log('mongodb connection = ' + url);
mongoose.connect(url, function(err) {
if(err) {
console.log('connection error: ', err);
} else {
console.log('connection successful');
}
});
/***********
Declare all models here
***********/
//User model
var UserSchema = new mongoose.Schema({
_id: mongoose.Schema.ObjectId,
username: String,
password: String
});
var User = mongoose.model('user', UserSchema);
/***********
All routes go below
***********/
app.get('/', function (req, res, next){
res.sendFile( __dirname + '/index.html');
});
app.get('/register', function (req, res, next) {
res.sendFile( __dirname + '/register.html');
});
app.post('/register', function (req, res, next) {
User.create(req.body, function(err, saved) {
if(err) {
console.log(err);
res.json({ message : err });
} else {
res.json({ message : "User successfully registered!"});
}
});
});
app.listen(port, '0.0.0.0', function(){
console.log('Server running at port ' + port);
});

//register.html file
<html>
<head>
<title>My first NodeJS Website</title>
</head>
<body>
<p>Registration page</p>
<form action="/register" method="post">
<p>Username <input type="text" name="username" /></p>
<p>Password <input type="password" name="password" /></p>
<input type="submit" value="Register"/>
</form>
<p><a href="/">Click here to go back.</a> </p>
</body>
</html>
&#13;
//index.html file
<html>
<head>
<title>My first NodeJS Website</title>
</head>
<body>
<p>Hello World!</p>
<form action="/login" method="post">
<p>Username <input type="text" name="username" /></p>
<p>Password <input type="password" name="password" /></p>
<input type="submit" value="Login"/>
</form>
<p>Not yet registered? <a href="/register">Click here to create an account.</a> </p>
</body>
</html>
&#13;
答案 0 :(得分:1)
您无需在_id
架构中将mongoose.Schema.ObjectId
定义为User
。即使您没有为_id
提供值,即使您未在架构中定义ID并插入对象,MongoDB也会隐式生成ID。但是,如果您在模式中显式定义它,Mongoose会运行验证检查并希望您提供该值 - 它将引发错误,您的查询甚至无法访问数据库。