Получаю ошибку с промисами и не соединяет с базой MongoAtlas

267
18 мая 2018, 12:00

Я создаю свой API сервер для интернет магазина на Node.js и у меня перестало присоединять к удаленной БД MongoAtlas.Вот такую ошибку я получаю:

(node:7696) UnhandledPromiseRejectionWarning: MongoNetworkError:
connection 4 to rest-shop-shard-00-00-e3hfo.mongodb.net:27017 closed
    at TLSSocket.<anonymous> (X:\projects\BranD(server)\node_modules\mongodb-core\lib\connection\connection.js:275:9)
    at Object.onceWrapper (events.js:272:13)
    at TLSSocket.emit (events.js:185:15)
    at _handle.close (net.js:538:12)
    at TCP.done [as _onclose] (_tls_wrap.js:379:7)
(node:7696) 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(). (rejection id: 1)
(node:7696) [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.

appl.js

const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const productRoutes = require('./api/routes/products');
const orderRoutes = require('./api/routes/orders');
mongoose.connect('mongodb://admin:admin@rest-shop-shard-00-00-e3hfo.mongodb.net:27017,rest-shop-shard-00-01-e3hfo.mongodb.net:27017,rest-shop-shard-00-02-e3hfo.mongodb.net:27017/test?ssl=true&replicaSet=Rest-shop-shard-0&authSource=admin');
mongoose.Promise = global.Promise;
app.use(morgan('dev'));
app.use('/uploads',express.static('uploads'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use((req,res,next)=>{
    res.header('Access-Control-Allow-Origin','*');
    res.header('Access-Control-Allow-Headers',
    'Origin, X-Requested-Width, Content-Type, Accept, Authorization');
if (req.method === 'OPTIONS'){
    res.header('Access-Control-Allow-Methods','PUT, POST, PATCH, DELETE, GET');
    return res.status(200).json({});    
}
next();
})
app.use('/products',productRoutes); 
app.use('/orders',orderRoutes); 
app.use((req,res,next)=>{
    const error = new Error('Not found');
    error.status = 404;
    next(error);
});
app.use((error,req,res,next)=>{
    res.status(err.status || 500);
    res.json({
        error:{
            message: error.message
        }
    })
})
module.exports = app;

products.js

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const multer = require('multer');
const storage = multer.diskStorage({
    destination: function (req,file,cb) {
        cb(null,'./uploads/');
    },
    filename:function (req,file,cb) {
        cb(null,new Data().toISOString() + file.originalname);
    }
});
const fileFilter = (req,file,cb) => {
    if(file.mimetype ==='image/jpeg' || file.mimetype ==='image/png'){
        cb(null,true);
    } else {
        cb(null,false);
    }
}
const upload = multer({
    storage:storage,
    limits:{
    fieldSize:1024 * 1024 * 5
    },
    fileFilter:fileFilter
});

const Product = require('../models/products');
router.get('/',(req,res,next)=>{
    Product.find()
    .select(' name price _id productImage ')
    .exec()
    .then(docs => {
        const response = {
            count: docs.length,
            products: docs.map(dic => {
                return{
                    name: doc.name,
                    price: doc.price,
                    productImage: doc.productImage,
                    _id: doc._id,
                    request: {
                        type: 'GET',
                        url: 'http' + doc._id
                    }
                }
            })
        }
        if (docs.length >= 0){
            res.status(200).json(response);
        }else{
            res.status(404).json({
                message: 'No entries found'
            });
        }
    })
    .catch(err =>{
        console.log(err);
        res.status(500).json({
            error: err
        })
    });
});
router.post('/',upload.single('productImage'),(req,res,next)=>{
    console.log(req.file);
    const product = new Product({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price,
        productImage: req.file.path
    });
    product
        .save()
        .then(result => {
        console.log(result);
        res.status(201).json({
            message: 'Created poduct succesfull',
            createdProduct: {
                name: result.name,
                price: result.price,
                _id: result._id,
                request:{
                    type: 'POST',
                    url: 'http' + result._id
                }
            }
        });
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        })
    });
});
router.get('/:productid',(req,res,next)=>{
    const id = req.params.productid;
        Product.findById(id)
        .select('name price _id productImage')
        .exec()
        .then(doc => {
            if (doc) {
                res.status(200).json({
                    message: 'Its you product with id' + doc._id,
                    name: doc.name,
                    price: doc.price,
                    request:{
                        type: 'GET',
                        url: 'http' + result._id
                    }
                });
            }else{
                res.status(404).json({
                    message: 'No valid entry found for provided ID'
                });
            }
        })
        .catch(err => {
            console.log(err)
            res.status(500).json({err:err})
        });
    });
router.patch('/:productid',(req,res,next)=>{
    const id = req.params.productid;
    const updateOps = {};
    for (const ops of req.body){
        updateOps[ops.propName] = ops.value;
    }
    Product.update({_id: id},{$set:updateOps})
    .exec()
    .then(result => {
        console.log(result);
        res.status(200).json({
            message: 'Product' + result._id + 'updated',
            request: {
                type: 'Update',
                url: 'http' + result._id,
                body: {
                    name: 'String',
                    price: 'Number'
                } 
            }
        })
    })
    .catch(err => {
        console.log(err);
        res.status(200).json(result);
    });
});
router.delete('/:productid',(req,res,next)=>{
    const id = req.params.productid;
    Product.remove({_id: id})
    .exec()
    .then( result => {
        res.status(200).json({
            message: 'Product' + result._id + ' deleted',
            request: {
                type: 'Delete',
                url: 'http' + result._id,
                body: {
                    name: 'String',
                    price: 'Number'
                } 
            }
        })
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });
});
module.exports = router;

Подскажите пожалуйста как исправить проблему.

READ ALSO
Таска по angulerjs

Таска по angulerjs

Задачка вроде не сложная, но я больше по реакту, а таску надо решить очень срочноПосле 0 в конце строки обратно появляется 10 (в Title (10 символов),...

226
JS weather description

JS weather description

В настоящее время разбираюсь с заданием

211
Какой принцип ООП реализуют замыкания?

Какой принцип ООП реализуют замыкания?

Я бы ответил: наследование и полиморфизмПример наследования: в функции можно использовать внешние переменные

217
Прототипное наследование в JS

Прототипное наследование в JS

Сначала я думал, что разобрался с прототипным наследованием в JS (ведь оно такое простое), а теперь мне кажется, что я не понимаю, зачем все это...

402