gpt4 book ai didi

node.js - Mongoose 错误 : document must have an _id before saving at new MongooseError

转载 作者:行者123 更新时间:2023-12-05 08:54:29 48 4
gpt4 key购买 nike

<分区>

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

当我点击“注册”按钮时,它加载了一个错误页面。 register error

这也会导致终端出现 Mongoose 错误,提示 MongooseError: document must have an _id before saving at new MongooseError

enter image description here

下面是代码。

//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>

//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>

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com