node.js - Node.js mongoose 无法在 MongoDB 数据库上“保存()”文档
问题描述
我的问题很奇特,因为我相信所有事情都是“按部就班”完成的。
我能够成功连接到我通过 MongoDB Atlas 创建的 MongoDB 集群。当我发出“POST”请求以保存从一系列选项中选择的选项时,我通过下面指定的模型成功创建了一个文档。然后我尝试通过调用“save()”方法将该文档保存到 MongoDB,但它挂起并且没有任何结果(即使我使用“catch”来查看是否发生任何错误)。
我完全不知道出了什么问题,以及我需要做些什么来解决这个问题。我希望你能给我一些指示。
MongoDB 连接、模式和模型:
const mongoose = require('mongoose');
const URL = process.env.MONGODB_URL;
mongoose.connect(URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('Successfully connected to our MongoDB database.');
}).catch((error) => {
console.log('Could not connect to our MongoDB database.', error.message);
});
const choicesMadeSchema = new mongoose.Schema({
allChoices: Array,
pickedChoice: String
});
const ChoiceMade = mongoose.model('ChoiceMade', choicesMadeSchema);
module.exports = ChoiceMade; // Exports our 'ChoiceMade' constructor, to be used by other modules.
index.js:
/* 1 - Setting things up */
require('dotenv').config();
const express = require('express');
const server = express();
const PORT = process.env.PORT;
const parserOfRequestBody = require('body-parser');
server.use(parserOfRequestBody.json());
/* 2 - Retrieving all the data we need from our 'MongoDB' database */
// Imports the 'mongoose' library, which will allow us to easily interact with our 'MongoDB' database.
const mongoose = require('mongoose');
// Imports our 'ChoiceMade' constructor.
const ChoiceMade = require('./database/database.js');
// Will hold the five latest choices that have been made (and thus saved on our 'MongoDB' database).
let fiveLatestChoicesMade;
// Retrieves the five latest choices that have been made (and thus saved on our 'MongoDB' database).
ChoiceMade.find({}).then((allChoicesEverMade) => {
const allChoicesEverMadeArray = allChoicesEverMade.map((choiceMade) => {
return choiceMade.toJSON();
});
fiveLatestChoicesMade = allChoicesEverMadeArray.slice(allChoicesEverMadeArray.length - 5).reverse();
console.log("These are the five latest choices that have been made:", fiveLatestChoicesMade);
mongoose.connection.close();
});
/* 3 - How the server should handle requests */
// 'GET' (i.e., 'retrieve') requests
server.get('/allChoicesMade', (request, response) => {
console.log("This is the data that will be sent as a response to the 'GET' request:", fiveLatestChoicesMade);
response.json(fiveLatestChoicesMade);
});
// 'POST' (i.e., 'send') requests
server.post('/allChoicesMade', (request, response) => {
const newChoiceMadeData = request.body;
if (Object.keys(newChoiceMadeData).length === 0) {
return response.status(400).json({ error: "No data was provided." });
}
const newChoiceMade = new ChoiceMade({
allChoices: newChoiceMadeData.allChoices,
pickedChoice: newChoiceMadeData.pickedChoice
});
console.log("This is the new 'choice made' entry that we are going to save on our 'MongoDB' database:", newChoiceMade); // All good until here
newChoiceMade.save().then((savedChoiceMade) => {
console.log('The choice that was made has been saved!');
response.json(savedChoiceMade);
mongoose.connection.close();
}).catch((error) => {
console.log('An error occurred:', error);
});
});
/* 4 - Telling the server to 'listen' for requests */
server.listen(PORT, () => {
console.log("Our 'Express' server is running, and listening for requests made to port '" + PORT + "'.");
});
问题的解决方案
在我的代码的第 2 节中,我在检索使我的应用程序运行所需的所有数据时错误地关闭了连接。我正在这样做(...)
// Retrieves the five latest choices that have been made (and thus saved on our 'MongoDB' database).
ChoiceMade.find({}).then((allChoicesEverMade) => {
const allChoicesEverMadeArray = allChoicesEverMade.map((choiceMade) => {
return choiceMade.toJSON();
});
fiveLatestChoicesMade = allChoicesEverMadeArray.slice(allChoicesEverMadeArray.length - 5).reverse();
console.log("These are the five latest choices that have been made:", fiveLatestChoicesMade);
mongoose.connection.close(); // This should not be here!!!
});
(...) 当我应该做的时候
// Retrieves the five latest choices that have been made (and thus saved on our 'MongoDB' database).
ChoiceMade.find({}).then((allChoicesEverMade) => {
const allChoicesEverMadeArray = allChoicesEverMade.map((choiceMade) => {
return choiceMade.toJSON();
});
fiveLatestChoicesMade = allChoicesEverMadeArray.slice(allChoicesEverMadeArray.length - 5).reverse();
console.log("These are the five latest choices that have been made:", fiveLatestChoicesMade);
// Now that I don't have mongoose.connection.close(), everything's OK!
});
基本上,在我的特殊情况下,我在从中检索数据后关闭了与 MongoDB 数据库的连接,然后当我不再与它建立连接时尝试向它添加一条新记录。
解决方案
推荐阅读
- c++ - 运算符重载使用运算符 + 为类模板添加
- exception - 异常向量是中断向量的更好名称吗?(在 ARM 的上下文中)
- swift - SwiftUI NavigationLink - “懒惰”的目的地?或者如何不编码重复的“标签”?
- c - 我从一位同事那里看到了一些有趣的代码。我很困惑发生了什么。它是哪个标准?我没能在 GOOGLE 中找到答案
- c++ - “警告:数组索引表达式中的逗号”但逗号分隔函数参数
- python-3.x - Opencv findCountours 函数
- swift - 如何在 SwiftUI 中使用 ForEach 仅更改一个核心数据项的切换?
- javascript - 从 NodeJS 中的本地文件路径返回一个 File 对象
- reactjs - 使用样式化组件在 React App 中滚动切换基于主题的图像
- javascript - 在javascript中将Oct转换为字符串中的文本