我正在编写我的节点应用程序的注册用户功能。我打电话连接到 mongodb 数据库。但是,当我使用该User.findOne({ email: req.body.email })
功能搜索数据库时,我的功能会卡在该步骤上。我使用 postmate 发送请求,我可以发送console.log()
请求正文
用户路线:
router.post("/register", async (req, res) => {
console.log("in here");
user = await User.findOne({ email: req.body.email })
.then(user => {
console.log("in here");
if (user) {
console.log("2");
return res.status(400).json({ email: "Email address already exists" });
} else {
const newUser = new User({
first: req.body.first,
last: req.body.last,
email: req.body.email,
password: req.body.password
});
我的用户模型:
const UserSchema = new mongoose.Schema({
name: {
type: String,
trim: true
},
first: {
type: String,
trim: true,
required: "First Name Required"
},
last: {
type: String,
trim: true,
required: "Last Name Required"
},
email: {
type: String,
unique: true,
lowercase: true,
trim: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = User = mongoose.model("User", UserSchema);
我的mogo客户端:
const MongoClient = require("mongodb").MongoClient;
const databaseUri = require("../config/keys").mongoURI;
const connect = () => {
return new Promise((resolve, reject) => {
MongoClient.connect(
databaseUri,
{ useNewUrlParser: true },
(err, client) => {
if (err) {
reject("Unable to connect to MongoDB server");
console.log(err);
}
client.close();
}
);
});
};
module.exports = {
connect
};
服务器.js
const express = require("express");
const http = require("http");
const mongoClient = require("./database/mongoClient");
const routes = require("./routes");
const app = express();
app.set("port", process.env.PORT || 3000);
app.get("/", (req, res) => res.send("Hello World 3"));
//connect to database
mongoClient.connect();
//initialize routes
routes.init(app);
http.createServer(app).listen(app.get("port"), function() {
console.log("Express server listening on port " + app.get("port"));
});