Продолжайте получать "UnhandledPromiseRejectionWarning", которое выбрасывает меня из node.js - PullRequest
0 голосов
/ 09 апреля 2020

Я пытаюсь подключиться к своему серверу, используя Mon goose, и запускаю файл приложения. js с помощью Node. Первоначально все прошло нормально, и мой файл был запущен на Node без проблем, но позже я начал получать «Предупреждение о необработанном обещании отказа», которое выбрасывает меня из Node каждый раз, когда я пытаюсь запустить файл. Это ошибки, которые я получаю в своем терминале, каждый раз, когда я пытаюсь запустить 'приложение узла. js':

(node:20496) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connection timed out
    at new MongooseServerSelectionError (C:\Users\ינון\desktop\web-development\fruitsProject\node_modules\mongoose\lib\error\serverSelection.js:22:11)
    at NativeConnection.Connection.openUri (C:\Users\ינון\desktop\web-development\fruitsProject\node_modules\mongoose\lib\connection.js:823:32)
    at Mongoose.connect (C:\Users\ינון\desktop\web-development\fruitsProject\node_modules\mongoose\lib\index.js:333:15) 
    at Object.<anonymous> (C:\Users\ינון\desktop\web-development\fruitsProject\app.js:3:10)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47
(node:20496) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:20496) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Вот весь код, который есть в моем приложении. js файл (файл, который я пытаюсь запустить с Node).

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/fruitsDB', {useUnifiedTopology: true, useNewUrlParser: true});

const fruitSchema = new mongoose.Schema({
    name: String,
    rating: Number,
    review: String
  });

  const Fruit = mongoose.model("Fruit", fruitSchema);

  const fruit = new Fruit ({
      name: "Apple",
      rating: 7,
      review: "Pretty solid as a fruit"
  })

  //fruit.save();

  const personSchema = new mongoose.Schema({
      name: String,
      age: Number
  })

  const Person = mongoose.model("Person", personSchema);

  const person = new Person({
      name: "John",
      age: 33
  })

  //person.save();

  const kiwi = new Fruit ({
    name: "Kiwi",
    rating: 7,
    review: "it's okay"
})

const orange = new Fruit ({
    name: "Orange",
    rating: 4,
    review: "Ew"
})

const banana = new Fruit ({
    name: "Banana",
    rating: 2,
    review: "wtf"
})

// Fruit.insertMany([kiwi, orange, banana], function(err) {
//     if(err) {
//         console.log(err);
//     }
//     else {
//         console.log("Successfully saved all fruits to fruitsDB.");
//     }
// })

Fruit.find(function(err, fruits) {
    if(err) {
        console.log(err);
    }
    else {
        console.log(fruits);
    }
})



const findDocuments = function(db, callback) {
    // Get the documents collection
    const collection = db.collection('fruits');
    // Find some documents
    collection.find({}).toArray(function(err, fruits) {
      assert.equal(err, null);
      console.log("Found the following records");
      console.log(fruits)
      callback(fruits);
    });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...