Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js mongoose无法';save()';关于MongoDB数据库的文档_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

Node.js mongoose无法';save()';关于MongoDB数据库的文档

Node.js mongoose无法';save()';关于MongoDB数据库的文档,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我的问题很奇怪,因为我相信一切都是“按部就班”的 我能够成功地连接到通过MongoDB Atlas创建的MongoDB集群。当我发出“POST”请求以保存从选项数组中选择的选项时,我通过下面指定的模型成功地创建了一个文档。然后,我尝试通过调用“save()”方法将该文档保存到MongoDB,但它会挂起,并且不会产生任何结果(即使我使用“catch”来查看是否发生任何错误) 我完全不知道是什么错了,我需要做什么来解决这个问题。我希望你能给我一些建议 MongoDB连接、模式和模型: const m

我的问题很奇怪,因为我相信一切都是“按部就班”的

我能够成功地连接到通过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.
/* 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 + "'.");
});
index.js:

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.
/* 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);

  // Now that I don't have mongoose.connection.close(), everything's OK!
});

基本上,在我的特殊情况下,我在从MongoDB数据库检索数据后关闭了与它的连接,然后在我不再与它有连接时尝试向它添加一条新记录。

这行是
console.log(“这是已经做出的五个最新选择:”,FivelatestChoicesMake)打印结果?你好@andresmunozit!它打印一个空数组,因为我没有关于数据库的任何信息。我试图通过POST请求添加它,然后通过GET请求检索它。谢谢这是一行
console.log(“这是已经做出的五个最新选择:”,FivelatestChoicesMake)打印结果?你好@andresmunozit!它打印一个空数组,因为我没有关于数据库的任何信息。我试图通过POST请求添加它,然后通过GET请求检索它。谢谢