У меня проблема, это мой код для logic.js
const mongoose = require('mongoose'); // An Object-Document Mapper for Node.js
const assert = require('assert'); // N.B: Assert module comes bundled with Node.js.
mongoose.Promise = global.Promise; // Allows us to use Native promises without throwing error.
// Connect to a single MongoDB instance. The connection string could be that of a remote server
// We assign the connection instance to a constant to be used later in closing the connection
const db = mongoose.connect('mongodb://localhost:27017/contact-manager', { useNewUrlParser: true });
// Converts value to lowercase
function toLower(v) {
return v.toLowerCase();
}
// Define a contact Schema
const contactSchema = mongoose.Schema({
firstname: { type: String, set: toLower },
lastname: { type: String, set: toLower },
phone: { type: String, set: toLower },
email: { type: String, set: toLower }
});
// Define model as an interface with the database
const Contact = mongoose.model('Contact', contactSchema);
/**
* @function [addContact]
* @returns {String} Status
*/
const addContact = (contact) => {
Contact.create(contact, (err) => {
assert.equal(null, err);
console.info('New contact added');
db.disconnect();
});
};
/**
* @function [getContact]
* @returns {Json} contacts
*/
const getContact = (name) => {
// Define search criteria. The search here is case-insensitive and inexact.
const search = new RegExp(name, 'i');
Contact.find({$or: [{firstname: search }, {lastname: search }]})
.exec((err, contact) => {
assert.equal(null, err);
console.info(contact);
console.info(`${contact.length} matches`);
db.disconnect();
});
};
// Export all methods
module.exports = { addContact, getContact };
и это для contact.js
const program = require('commander');
// Require logic.js file and extract controller functions using JS destructuring assignment
const { addContact, getContact } = require('./logic');
program
.version('0.0.1')
.description('Contact management system');
program
.command('addContact <firstame> <lastname> <phone> <email>')
.alias('a')
.description('Add a contact')
.action((firstname, lastname, phone, email) => {
addContact({firstname, lastname, phone, email});
});
program
.command('getContact <name>')
.alias('r')
.description('Get contact')
.action(name => getContact(name));
program.parse(process.argv);
когда я запускаю в терминале 'узел contact.js addContact John Doe 013-452-3134 john.doe@contacto.com', он показывает это:
(узел: 17453) UnhandledPromiseRejectionWarning: MongoNetworkError: не удалось подключиться к серверу [localhost: 27017] при первом подключении [MongoNetworkError: подключить ECONNREFUSED 127.0.0.1:27017] в пуле.(/home/akbar/projecttt/node_modules/mongodb-core/lib/topologies/server.js:564:11) в Pool.emit (events.js: 182: 13) в Connection.(/home/akbar/projecttt/node_modules/mongodb-core/lib/connection/pool.js:317:12) в Object.onceWrapper (events.js: 273: 13) в Connection.emit (events.js: 182:13) у розетки.(/home/akbar/projecttt/node_modules/mongodb-core/lib/connection/connection.js:246:50) в Object.onceWrapper (events.js: 273: 13) в Socket.emit (events.js: 182:13) в emitErrorNT (внутренний / streams / destroy.js: 82: 8) в emitErrorAndCloseNT (внутренний / streams / destroy.js: 50: 3) в process._tickCallback (внутренний / process / next_tick.js: 63: 19) (узел: 17453) UnhandledPromiseRejectionWarning: необработанное отклонение обещания.Эта ошибка возникла либо из-за того, что внутри асинхронной функции возникла ошибка без блока catch, либо из-за отклонения обещания, которое не было обработано с помощью .catch ().(идентификатор отклонения: 1) (узел: 17453) [DEP0018] Предупреждение об устаревании: отклонения необработанного обещания устарели.В будущем отклонения обещаний, которые не обрабатываются, завершат процесс Node.js с ненулевым кодом выхода.
Может кто-нибудь мне помочь?