connect the mongodb remote server Error : UnhandledPromiseRejectionWarning - node.js

I have following error occurred
UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 1): MongoError: E11000 duplicate key error collection:
LearningLocker_V2.statements index: id_1 dup key: { : null }
My code is
var express = require('express');
var app = express();
const xapi = require('vtc-lrs');
app.use("/xapi", new xapi());
let options = {
lrs: new xapi.LRS(),
connectionString: "mongodb://192.168.1.38:27017/LearningLocker_V2",
getUser: function (req, username, password) {
return new xapi.Account("lrsuser", "test123", true, true);
},
baseUrl: "http://localhost:8010/xapi"
};
app.use("/xapi", new xapi(options));
In the above code, I connect the mongodb remote server but it's not working. one more thing i use the xapi vts-lrs so don't know how to work with this.

Related

Keep getting the "ConfigError: Missing region in config" error in Node.js no matter what I do

I keep getting the "UnhandledPromiseRejectionWarning: ConfigError: Missing region in config" when trying to make requests to APIs I have set up in Node.js.
I'm new to DynamoDB and after setting up most of my boilerplate code I'm using Postman to test my routes. However I keep getting the same error each time I make a post request. I've checked some solutions on existing threads, namely: Configuring region in Node.js AWS SDK but cannot get it to work.
I am currently developing the app locally and checked the database where the items are being added.
My setup is as follows:
// user_controller.js
const uuid = require('uuid');
const sanitizer = require('validator');
const bcrypt = require('bcryptjs-then');
const AWS = require('aws-sdk');
const config = require('../config/config');
const { signToken, userByEmail, userById } = require('../Helpers/Users');
const isDev = true
Then in my code block I have the following:
// user_controller.js
(...)
if (isDev) {
AWS.config.update(config.aws_local_config);
} else {
AWS.config.update(config.aws_remote_config);
}
const DB = new AWS.DynamoDB.DocumentClient();
const params = {
TableName: config.aws_table_name,
Item: {
userId: await uuid.v1(),
firstName: sanitizer.trim(firstName),
lastName: sanitizer.trim(lastName),
email: sanitizer.normalizeEmail(sanitizer.trim(email)),
password: await bcrypt.hash(password, 8),
level: 'standard',
createdAt: new Date().getTime(),
updatedAt: new Date().getTime(),
},
}
return userByEmail(params.Item.email) // Does the email already exist?
.then(user => { if (user) throw new Error('User with that email exists') })
.then(() => DB.put(params).promise()) // Add the data to the DB
.then(() => userById(params.Item.id)) // Get user data from DB
.then(user => (err, data) => {
console.log("AFTER USER CREATED")
if (err) {
res.send({
success: false,
message: 'Error: Server error'
});
} else {
console.log('data', data);
res.send({
statusCode: 201,
message: 'Success - you are now registered',
data: { token: signToken(params.Item.id), ...user },
});
}
})
(...)
Finally I am importing the config from separate file:
// config.js
module.exports = {
aws_table_name: 'usersTable',
aws_local_config: {
region: 'local',
endpoint: 'http://localhost:8000'
},
aws_remote_config: {}
}
In have already configured the aws-sdk:
AWS Access Key ID [****************foo]:
AWS Secret Access Key [****************bar]:
Default region name [local]:
Default output format [json]:
Here is the output I keep getting:
(node:4568) UnhandledPromiseRejectionWarning: ConfigError: Missing region in config
at Request.VALIDATE_REGION (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:92:45)
at Request.callListeners (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
at callNextListener (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/sequential_executor.js:96:12)
at /Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:86:9
at finish (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:350:7)
at /Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:368:9
at SharedIniFileCredentials.get (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/credentials.js:127:7)
at getAsyncCredentials (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:362:24)
at Config.getCredentials (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:382:9)
at Request.VALIDATE_CREDENTIALS (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:81:26)
(node:4568) 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: 4)
(node:4568) [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.
Like I said, I've tried a lot of variations on this but to no avail. Would love some help, thanks.
I dont know if this helps, but I used none instead of local for the region and it seemed to work for me
AWS.config.update({ region: 'none' })

UnhandledPromiseRejectionWarning: Error: Network error: apollo_cache_inmemory_1.readQueryFromStore is not a function aws appsync nodejs

I am trying to call an Graphql Query for my AWS AppSync app through nodejs. The error I am encountering is
UnhandledPromiseRejectionWarning: Error: Network error:
apollo_cache_inmemory_1.readQueryFromStore
This is my index.js code
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var config = {
AWS_ACCESS_KEY_ID: <ACCESS_KEY_ID>,
AWS_SECRET_ACCESS_KEY: <SECRET_KEY>,
HOST: '<HOST_URL>',
REGION: 'us-west-2',
PATH: '/graphql',
ENDPOINT: '<AWS_APPSYNC_ENDPOINT>',
};
config.ENDPOINT = "https://" + config.HOST + config.PATH;
exports.default = config;
global.localStorage = {
store: {},
getItem: function (key) {
return this.store[key]
},
setItem: function (key, value) {
this.store[key] = value
},
removeItem: function (key) {
delete this.store[key]
}
};
require('es6-promise').polyfill();
require('isomorphic-fetch');
// Require AppSync module
const AUTH_TYPE = "AWS_IAM";
const AWSAppSyncClient = require('aws-appsync').default;
const url = config.ENDPOINT;
const region = config.REGION;
const type = AUTH_TYPE.AWS_IAM;
// If you want to use API key-based auth
const apiKey = 'xxxxxxxxx';
// If you want to use a jwtToken from Amazon Cognito identity:
const jwtToken = 'xxxxxxxx';
// If you want to use AWS...
const AWS = require('aws-sdk');
AWS.config.update({
region: config.REGION,
credentials: new AWS.Credentials({
accessKeyId: config.AWS_ACCESS_KEY_ID,
secretAccessKey: config.AWS_SECRET_ACCESS_KEY
})
});
const credentials = AWS.config.credentials;
// Import gql helper and craft a GraphQL query
const gql = require('graphql-tag');
const query = gql(`
query {
getSample {
mobileNumber
}
}
`);
// Set up Apollo client
const client = new AWSAppSyncClient({
url: url,
region: region,
auth: {
type: type,
credentials: credentials,
}
});
client.hydrated().then(function a(client) {
client.query({query: query});
client.query({ query: query, fetchPolicy: 'network-only'}).then(function(data) {
console.log("data: " + queryResult);
})
});
The complete stacktrace is the following:
UnhandledPromiseRejectionWarning: Error: Network error:
apollo_cache_inmemory_1.readQueryFromStore is not a function
at new ApolloError (/Users/kanhaiagarwal/appsync1/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:124:32)
at /Users/kanhaiagarwal/appsync1/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:1248:45
at /Users/kanhaiagarwal/appsync1/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:1680:21
at Array.forEach ()
at /Users/kanhaiagarwal/appsync1/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:1679:22
at Map.forEach ()
at QueryManager.broadcastQueries (/Users/kanhaiagarwal/appsync1/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:1672:26)
at /Users/kanhaiagarwal/appsync1/node_modules/aws-appsync/node_modules/apollo-client/bundle.umd.js:1175:35
at (node:23377) 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:23377) [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.
Can someone suggest a solution for this?
The problem is caused by not providing a window object that the aws-appsync package relies on for some global objects. This is not present in the Node.js environment and adding the following at the start of your script should make it work:
global.window = global.window || {
setTimeout: setTimeout,
clearTimeout: clearTimeout,
WebSocket: global.WebSocket,
ArrayBuffer: global.ArrayBuffer,
addEventListener: function () { },
navigator: { onLine: true }
};
Here's the GitHub issue where the answer was proposed:
https://github.com/awslabs/aws-mobile-appsync-sdk-js/issues/276#issuecomment-432983691

CloudSQL connection issues with deployed Bookshelf tutorial app (App Engine/NodeJS)

I deployed my code on app engine with node js (flex environment).
config.json
{
"GCLOUD_PROJECT": "XXXXXX",
"DATA_BACKEND": "cloudsql",
"MYSQL_USER": "XXXX",
"MYSQL_PASSWORD": "XXXXX",
"INSTANCE_CONNECTION_NAME": "XXXXXX:us-central1:XXXXX"
}
model-cloudsql.js
const options = {
user: config.get('MYSQL_USER'),
password: config.get('MYSQL_PASSWORD'),
database: 'XXXXX'
};
if (config.get('INSTANCE_CONNECTION_NAME') && config.get('NODE_ENV') === 'production') {
options.socketPath = `/cloudsql/${config.get('INSTANCE_CONNECTION_NAME')}`;
}
const connection = mysql.createConnection(options);
I am getting below error:
"Cannot enqueue Query after fatal error."
please provides any feedback on it.
It looks like the error "Cannot enqueue Query after fatal error." happens when you try to query a connection that encounter a fatal error during create. If we check out the mysqljs documentation, it recommends connecting with the following:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
As you can see, you need to pass along a callback function to handle any errors that may arise while you are attempting to connect. This callback function will print the error encountered to give you more info on why it failed to connect.
Additionally, you may be interested in this section on handling errors.

How to access AWS Elasticsearch from Node JS

I have my nodejs lambda trying to index data into ES, but it's failing because of this error:
2018-01-15T23:39:09.578Z (node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 131): Authorization Exception ::
User: anonymous is not authorized to perform: es:ESHttpPost on resource: ****
I have applied AmazonESFullAccess policy to the Lambda function role.
What am I missing?
I was able to resolve this issue. Code was missing 'connectionClass' and 'amazonES' parameters.
var AWS = require('aws-sdk');
var connectionClass = require('http-aws-es');
var elasticsearch = require('elasticsearch');
var elasticClient = new elasticsearch.Client({
host: ***,
log: 'error',
connectionClass: connectionClass,
amazonES: {
credentials: new AWS.EnvironmentCredentials('AWS')
}
});

Node.js "Error: read ECONNRESET"

I am trying to connect to mongo via Node.js and I'm getting the following error:
connection error: { Error: read ECONNRESET
at exports._errnoException (util.js:1022:11)
at TCP.onread (net.js:610:25) name: 'MongoError', message: 'read ECONNRESET' }
(node:3868) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: read ECONNRESET
Here is the code I'm using to connect:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
module.exports = (config) => {
const fs = require('fs');
let key = fs.readFileSync('../server/test/keys/cert_key.pem');
let ca = [fs.readFileSync('../server/test/keys/ca.pem')];
let o = {
server: {
sslValidate: true,
sslCA: ca,
sslKey: key,
sslCert: key
}
};
mongoose.connect(config.connectionString, o);
let database = mongoose.connection;
database.on('error', console.error.bind(console, 'connection error:'))
database.once('open', (error) => {
if (error) {
console.log(error);
return;
}
console.log('MongoDB ready!')
});
require('./../models/Role').initialize();
require('./../models/User');
require('./../models/Item');
require('./../models/character/Character_item');
require('./../models/Article');
require('./../models/Friend_request');
require('./../models/Code');
require('./../models/Ring');
require('./../models/Ring_shop');
require('./../models/Comment');
};
If I try to connect to mongo from Robo3T, it works. So it seems the problem is in my Node code. Any suggestions?
Accordin mongoDB node driver documentation you must pass ssl: true in the server option in order to connect via SSL otherwise SSL is ignored.
My standard ssl db options is the following :
server: {
ssl: true,
sslValidate:true,
sslCA: ca,
ca: ca,
sslKey: key,
sslCert: key
}
I was having the same issue as I was working on the cloud provided by MongoDB. The reason it was happening with me was that I have configured my home IP to be connected and not my work IP. After adding my work IP in the cloud settings I was able to connect
Confirm that your mongodb database's file is not damaged。If .wt file has damaged, you'll got that error. The .wt filen in your storage path. eg:
storage:
dbPath: E:\Data\mongodb
You can use mongorestore command to repair data if you backuped before. otherwise you can drop the database and re-init a new one.

Resources