MongooseError:在新的 MongooseError 处保存之前,文档必须有一个 _id

Kev*_*Lee 2 mongoose mongodb node.js

我有一个注册页面,需要输入用户名和密码才能存储到 mongoDB 中。 注册画面

当我单击“注册”按钮时,它会加载一个错误页面。 注册错误

这也会在终端中导致 Mongoose 错误,显示 MongooseError: document must have an _id before save at new MongooseError

在此处输入图片说明

下面是代码。

//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);
});
Run Code Online (Sandbox Code Playgroud)

//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>
Run Code Online (Sandbox Code Playgroud)

//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>
Run Code Online (Sandbox Code Playgroud)

Tsv*_*nev 7

您不必在架构中定义_idas 。即使您没有在架构中定义它,MongoDB 也会隐式生成 ID 并插入您的对象,即使您没有为. 但是,如果您在架构中明确定义它,Mongoose 会运行验证检查并希望您提供该值 - 它会引发错误并且您的查询甚至不会到达数据库。mongoose.Schema.ObjectIdUser_id