Why are all my Mongoose requests timing out? - node.js

My Mongoose requests have all been timing out since yesterday.
My internet connection is working well, the same as usual, and my source code is unchanged.
So, I think it must be a problem with my dependencies or with MongoDB itself.
Minimal reproducible example:
const mongoose = require('mongoose')
const mongoURL = //replace this comment with your own Mongo URL
mongoose.connect(mongoURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})
const exampleSchema = new mongoose.Schema({
title: String,
author: String
})
const Example = mongoose.model('Example', exampleSchema)
const exampleOne = new Example({
title: 'Don Quixote',
author: 'M. Cervantes'
})
exampleOne.save().then(res => console.log(res))
mongoose.connection.close()
Full error trace from running the above example:
(node:18284) Warning: Accessing non-existent property 'MongoError' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
(node:18284) UnhandledPromiseRejectionWarning: MongooseError: Operation `examples.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (G:\Programming\Courses\Fullstack-Helsinki-2020\mongo_testing\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:185:20)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
(node:18284) 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:18284) [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.
(node:18284) DeprecationWarning: Listening to events on the Db class has been deprecated and will be removed in the next major version.
My current Mongoose and MongoDB versions (from package.json):
"mongoose": {
"version": "5.11.16",
"resolved": "https://registry.npmjs.org/mongoose/-/mongoose-5.11.16.tgz",
"integrity": "sha512-qmolyGAskPuq0Xr3j2Tjm9jwRccGGnLRWtTuyRvYBZoyItajwIoQdetJH8oVzs3N7aZK/GKZ82xV/t97suF8Pg==",
"requires": {
"#types/mongodb": "^3.5.27",
"bson": "^1.1.4",
"kareem": "2.3.2",
"mongodb": "3.6.4",
"mongoose-legacy-pluralize": "1.0.2",
"mpath": "0.8.3",
"mquery": "3.2.4",
"ms": "2.1.2",
"regexp-clone": "1.0.0",
"safe-buffer": "5.2.1",
"sift": "7.0.1",
"sliced": "1.0.1"
},
"dependencies": {
"mongodb": {
"version": "3.6.4",
"resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.6.4.tgz",
"integrity": "sha512-Y+Ki9iXE9jI+n9bVtbTOOdK0B95d6wVGSucwtBkvQ+HIvVdTCfpVRp01FDC24uhC/Q2WXQ8Lpq3/zwtB5Op9Qw==",
"requires": {
"bl": "^2.2.1",
"bson": "^1.1.4",
"denque": "^1.4.1",
"require_optional": "^1.0.1",
"safe-buffer": "^5.1.2",
"saslprep": "^1.0.0"
}
},
"safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="
}
}
Question: Why is the above example raising the above error, and, in general, why have my Mongoose requests all been timing out?

First you need to wait a connection to be established to make sure it will be ok, see Error handling:
try {
await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
} catch (error) {
handleError(error);
}
Second you need to call mongoose.connection.close() after save call will be either resolved or rejected:
exampleOne.save().then(res => {
console.log(res)
mongoose.connection.close()
})
because you didn't use await the save call didn't wait for resolve and mongoose.connection.close() was immediately called.
const res = await exampleOne.save()
console.log(res)
mongoose.connection.close()
})

As I said in comment and also #Anatoly said you should send request (i.e. save) after that connection was established.
const mongoose = require('mongoose')
const exampleSchema = new mongoose.Schema({
title: String,
author: String
})
const Example = mongoose.model('Example', exampleSchema)
const mongoURL = //replace this comment with your own Mongo URL
mongoose.connect(mongoURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})
.then(() => {
const exampleOne = new Example({
title: 'Don Quixote',
author: 'M. Cervantes'
})
exampleOne.save().then(res => {
console.log(res)
mongoose.connection.close()
})
})
.catch(err => {
// handle error
})

Related

How to resolve `buffering timed out after 10000ms` error in MongodoDB and Mongoose

I am using MongoDb in my Nodejs App with mongoose as ORM. However I am getting this error everytime I run my code.
(node:28316) UnhandledPromiseRejectionWarning: MongooseError: Operation `auths.findOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (/home/mridu/Projects/unoletter/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:149:23)
at listOnTimeout (internal/timers.js:557:17)
at processTimers (internal/timers.js:500:7)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:28316) 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: 2)
(node:28316) [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.
Here is my code to connect with MongoDb atlast
try {
mongoose.connect(
process.env.DB_URI,
{
keepAlive: true,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
},
() => {
console.log(`connected to MongoDB`);
}
);
} catch (error) {
console.log(error);
}
My model
//Dependencies
const mongoose = require("mongoose");
//Auth Model
const auth = {
id: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
secret: {
type: String,
required: true,
},
isVerified: Boolean,
createdAt: {
time: String,
date: String,
},
};
const Auth = mongoose.model("Auth", auth);
//Export
module.exports = { Auth };
And this is how I am saving my data
const auth = new Auth({
id: generateId(),
email: body.email,
secret: generateSecret(),
isVerified: false,
createdAt: {
time: dayjs().format("HH:mm:ss"),
date: dayjs().format("YYYY/MM/DD"),
},
});
try {
await auth.save();
console.log(auth);
} catch (error) {
console.log(error);
}
I have tried some answers from Stackoverflow and other websites like Dev.to. I have tried using async/await, .then & .catch. Still I am facing the same error.
Another project where I am using the 5.xx version of Mongoose is working fine. I am facing this issue with new 6.0.3 version of mongoose.
Make sure to call the function that uses the connection, an example can be the following.
I have the following function:
const start = async () => {
try {
await connectDB(process.env.MONGO_URI);
await Product.deleteMany();
await Product.create(jsonProducts);
// console.log(jsonProducts)
console.log('Conexion exitosa')
process.exit(0)
} catch (e) {
console.log(e)
process.exit(1)
}
}
It turned out that I was declaring the function but not using it, my solution was just to execute the start() function.

Deploy Node, Express, and MongoDB server to heroku

I created a server using Node, Express, and MongoDB Atlas. Here is the code of this:
server.js:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
// model
let Cards = require('./models/cards.model');
// App config
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
// DB config
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection has been established successfully.");
})
// API Endpoints
// POST parameter
app.post('/tinder/cards', (req, res) => {
const card = req.body;
Cards.create(card, (err, data) => {
if(err){
return res.status(500).send(err)
} else {
return res.status(200).send(data)
}
})
})
// GET parameter
app.get('/', (req, res) => {
return res.status(200).send("Welcome to Tinder Clone Backend with NodeJS, ExpressJS, and MongoDB!!!")
})
app.get('/tinder/cards', (req, res) => {
Cards.find((err, data) => {
if(err) {
return res.status(500).send(err);
} else {
return res.status(200).send(data)
}
})
});
// Listener
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
});
package.json
{
"name": "tinder-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.12.2"
}
}
cards.model.js
// creating database schema using mongoose
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const cardsSchema = new Schema({
name: String,
imgUrl: String
});
const Cards = mongoose.model('Cards', cardsSchema);
module.exports = Cards;
It is working locally and all endpoints sending and receiving data from mongodb atlas.
when I run this command in terminal to start the local server:
$ nodemon server
it is showing this:
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Server is running on port 5000
MongoDB database connection has been established successfully.
This means that my local server is running well and when I check in my browser and type in my server link i.e http://localhost:5000/tinder/cards, it showing data that I have posted previously:
[
{
"_id": "605a53881dedb514dcc1c4f2",
"name": "Elon Musk",
"imgUrl": "https://s3.india.com/wp-content/uploads/2020/03/Elon-Musk-AP.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f3",
"name": "Shakira",
"imgUrl": "https://ichef.bbci.co.uk/news/976/cpsprodpb/738B/production/_116497592_gettyimages-971720370.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f4",
"name": "Jeff Bezos",
"imgUrl": "https://media.wired.com/photos/6019cab23453f789506008d0/master/pass/Sec_Bezos_1036084400.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f5",
"name": "Dua Lipa",
"imgUrl": "https://assets.vogue.com/photos/5f48136693122510d16f0352/4:3/w_1080,h_810,c_limit/118520052_586967341971321_6121798062289952442_n.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f6",
"name": "Pitbull",
"imgUrl": "https://vz.cnwimg.com/wp-content/uploads/2010/03/Pitbull.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f7",
"name": "Ellen",
"imgUrl": "https://www.geo.tv/assets/uploads/updates/2021-03-18/340307_5260100_updates.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f8",
"name": "Bill Gates",
"imgUrl": "https://www.incimages.com/uploaded_files/image/1920x1080/getty_1185999101_20001333200092800_443629.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f9",
"name": "Taylor Swift",
"imgUrl": "https://static.onecms.io/wp-content/uploads/sites/20/2020/12/02/taylor-swift1.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4fa",
"name": "Engin Altan",
"imgUrl": "https://www.incpak.com/wp-content/uploads/2020/09/50094085_2224186024567959_693900883193935752_n.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4fb",
"name": "Esra Bilgic",
"imgUrl": "https://i.dawn.com/large/2021/01/6007fbceb61de.png",
"__v": 0
}
]
But when I deployed the same server to heroku, it is showing an empty object when I testing it.
When I run this command into my terminal:
$ heroku logs --tails
It is showing this error:
2021-03-25T11:08:08.715303+00:00 app[web.1]: (node:21) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: Could not connect to
any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted.
Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
2021-03-25T11:08:08.715323+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:839:32)
2021-03-25T11:08:08.715324+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:348:10
2021-03-25T11:08:08.715326+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
2021-03-25T11:08:08.715326+00:00 app[web.1]: at new Promise (<anonymous>)
2021-03-25T11:08:08.715327+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
2021-03-25T11:08:08.715328+00:00 app[web.1]: at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1152:10)
2021-03-25T11:08:08.715328+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:347:20)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Object.<anonymous> (/app/server.js:23:10)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1063:30)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
2021-03-25T11:08:08.715330+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:928:32)
2021-03-25T11:08:08.715330+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:769:14)
2021-03-25T11:08:08.715331+00:00 app[web.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
2021-03-25T11:08:08.715331+00:00 app[web.1]: at internal/main/run_main_module.js:17:47
2021-03-25T11:08:08.715332+00:00 app[web.1]: (Use `node --trace-warnings ...` to show where the warning was created)
2021-03-25T11:08:08.721117+00:00 app[web.1]: (node:21) 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 term
inate 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)
2021-03-25T11:08:08.721508+00:00 app[web.1]: (node:21) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the fut
ure, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
my server that is deployed on heroku is showing empty object instead of that data that I have posted,
when I type URL of heroku server i.e https://tinder-clone-backend-mern.herokuapp.com/tinder/cards :
{}
How can I make this server work perfectly as the local server does?
Try setting IPS, in your Atlas cluster/Network Access, to be available for all IPS (0.0.0.0/0) Let me know if it fixes.

Electron with strapi, Cannot find module package.json

I built an application using strapi, i am trying to package it inside electron using electron-builder.
The packaging is done well, but when i start the app, it shows this message
PS E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked>
(node:13196) UnhandledPromiseRejectionWarning: Error: Cannot find module 'E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\package.json'
Require stack:
- E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\node_modules\strapi\lib\Strapi.js
- E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\node_modules\strapi\lib\index.js
- E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\index.js
-
at Module._resolveFilename (internal/modules/cjs/loader.js:797:17)
at Function.o._resolveFilename (electron/js2c/browser_init.js:281:679)
at Module._load (internal/modules/cjs/loader.js:690:27)
at Function.Module._load (electron/js2c/asar.js:769:28)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at new Strapi (E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\node_modules\strapi\lib\Strapi.js:94:21)
at module.exports (E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\node_modules\strapi\lib\Strapi.js:564:18)
at createWindow (E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\index.js:23:5)
(node:13196) 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:13196) [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.
What seems to be the problem is that my application is looking to package.json file inside the root folder (directly relative to the exe file), while it exist inside the (app) folder with all other resources of the system.
this is my package.json file
{
"name": "DentalSys",
"main": "./index.js",
"version": "0.2.0",
"description": "Dental Clinic Management System",
"productName": "DentalSys",
"build": {
"appId": "com.kldoon.dentalSys",
"asar": false
},
"scripts": {
"develop": "strapi develop",
"strapi-start": "strapi start",
"strapi-prod": "cross-env NODE_ENV=production npm start",
"strapi-build": "strapi build",
.....
},
"devDependencies": {
"concurrently": "^5.1.0",
"electron": "^9.1.2",
"electron-builder": "^22.4.1",
......
},
"dependencies": {
"knex": "0.20.13",
"moment": "^2.27.0",
"sqlite3": "^4.1.1",
"strapi": "3.0.0-beta.17.5",
.......
}
And this is my electron (index.js) file
const { app, BrowserWindow, Menu, dialog } = require('electron')
const path = require("path");
const strapi = require('strapi');
//const { exec } = require("child_process");
function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
maximizable: true,
title: "Dental System",
webPreferences: {
nodeIntegration: true
}
})
win.maximize();
strapi().start().then(() => {
win.loadURL('http://localhost:49862/');
}).catch((e) => {
console.log(e);
});
win.on('closed', () => {
app.quit();
})
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
I tried multiple solutions but none work, i hope someone can help with it.
Thanks in advance.
It turned out to be easy fix, with dir option of strapi constructor
strapi({
dir: __dirname + '/' ///<==== add this
}).start().then(() => {
win.loadURL('http://localhost:1337/');
}).catch((e) => {
dialog.showMessageBox(win, { message: JSON.stringify(e) });
console.log(e);
});

`newSession` not found when using local capabilities

I'm facing this error when trying to use BrowserStack local capability:
(node:67602) UnhandledPromiseRejectionWarning: UnsupportedOperationError: newSession: Not Found
at parseHttpResponse (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:578:11)
at Executor.execute (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:489:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:67602) 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:67602) [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.
(node:67602) UnhandledPromiseRejectionWarning: UnsupportedOperationError: newSession: Not Found
at parseHttpResponse (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:578:11)
at Executor.execute (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:489:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:67602) 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: 3)
My code is pretty simple:
const webdriver = require('selenium-webdriver');
const browserstack = require('browserstack-local');
const runTestSuite = () => {
const capabilities = {
browserName: 'Chrome',
browser_version: '80.0 beta',
os: 'OS X',
os_version: 'Catalina',
resolution: '1024x768',
'browserstack.user': '<user>',
'browserstack.key': '<key>',
'browserstack.local': true,
'browserstack.localIdentifier': 'ardotest',
// 'browserstack.use_w3c': true,
acceptSslCerts: true,
name: 'Bstack-[Node] Sample Test-OS X Catalina-Chrome 80',
};
// https://www.browserstack.com/question/663
const driver = new webdriver.Builder()
.usingServer('http://localhost:3000') // tried using the IP that I got from Network settings on my machine, it spat out the same error
.withCapabilities(capabilities)
.build();
console.log('quit');
driver.quit();
};
// creates an instance of Local
const bsLocal = new browserstack.Local();
// replace <browserstack-accesskey> with your key. You can also set an environment variable - "BROWSERSTACK_ACCESS_KEY".
const bsLocalArgs = { key: '<browserstack-accesskey>' };
// https://github.com/browserstack/browserstack-local-nodejs/blob/master/lib/Local.js
// starts the Local instance with the required arguments
bsLocal.start(bsLocalArgs, function(err) {
if (err) {
console.error(err);
return;
}
if (!bsLocal.isRunning()) {
return;
}
try {
runTestSuite();
} catch (e) {
console.error(e);
} finally {
// stop the Local instance
bsLocal.stop(function(err) {
if (err) {
console.error(err);
}
console.log('===== BrowserStack tunnel stopped =====');
});
}
});
Versions:
"selenium-webdriver": "^4.0.0-alpha.5",
"browserstack-local": "^1.4.5",
My local environment:
"node": "10.16.3",
"npm": "6.8.0",
macOS 10.14.6
Looking through the code, it's clear that it's trying to hit /session url to create a new session or something. I'm not sure whether I should support /session manually, or I'm just missing something that's really stupid here?
It seems that BrowserStack provides it's own Hub URL for the test executions. You may try changing the hub URL from localhost:3000 to BrowserStacks hub url.
Referring to this code -> .usingServer('http://localhost:3000')
This document has more details: https://www.browserstack.com/local-testing/automate
You just need to make sure to have the same localIdentifier arg in both capabilities AND bsLocalArgs.
That is, both in .withCapabilities(<here>) and new browserstack.Local().start(<here>, ...)

Using the docs but completely confused... mongoose Model#save

I am trying to return specific status codes such as, 409 Conflict. I have used the Model#save docs
Edit: I am not trying to solve the error, it is deliberate.
According to the docs, there is three parameters on the callback: err, product, and numAffected.
EDIT: I wrote this code wrong and I edited. Either way, I got an excellent answer from Ryan.
app.post('/skill', (req, res) => {
const skill = new Skill({some_duplicate_object});
skill.save((err, product, numAffected) => {
console.log("Error: ", err);
});
NOT my console.log, in the Mocha test cli, I get an error:
(node:19760) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 5): ValidationError: Path `name` is required.
By playing around and shear luck, I did this: This is NOT in the mongoose docs and is my main reason for writing this post.
app.post('/skill', (req, res) => {
const skill = new Skill({});
skill.save()
.then((err, product, numAffected) => {
console.log("Nothing displayed here");
}, (err) => {
console.log(err.errors);
});
Even though this is not in the docs, it shows the error I want. As someone that is REALLY trying to use official docs more, I find it so hard to understand what is really going on. Why does this work and if it is in the docs, where would this info be?
{ name:
{ MongooseError: Path `name` is required.
at ValidatorError (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/error/validator.js:24:11)
at validate (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:706:13)
at /home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:752:11
at Array.forEach (native)
at SchemaString.SchemaType.doValidate (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:712:19)
at /home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/document.js:1408:9
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
message: 'Path `name` is required.',
name: 'ValidatorError',
properties:
{ type: 'required',
message: 'Path `{PATH}` is required.',
validator: [Function],
path: 'name',
value: undefined },
kind: 'required',
path: 'name',
value: undefined,
reason: undefined } }
Extra info:
"devDependencies": {
"chai": "^3.5.0",
"mocha": "^2.4.5",
"request": "^2.81.0",
"supertest": "^3.0.0"
},
"dependencies": {
"body-parser": "^1.17.1",
"express": "^4.15.2",
"mongoose": "^4.9.2"
}
Your problem is two fold, and both of the errors you are getting are telling you exactly what is wrong. The source of your troubles is lack of understanding (not trying to pick on you). This is kind of the same as if you were a beginner at electronics and I told your that a tube is biased improperly and you said "I don't understand" - well, you need to learn about tubes then because I just described to you the exact problem with your circuit.
1. Promise error - UnhandledPromiseRejectionWarning: Unhandled promise rejection.... This cannot be more descript. Promises are either 1) resolved or 2) rejected. If you fail to "handle" the rejected case, you will get an error. Handling a rejected promise can happen one of two ways:
// pass a 2nd function to `.then()`:
somePromise.then(function (result) {
// promise was "resolved" successfully
}, function (err) {
// Promise was "rejected"
});
// use `.catch()` - this is preferred in my opinion:
somePromise.then(function (result) {
// promise was "resolved" successfully
}).catch(function (err) {
// Promise was "rejected"
});
Using either of the above scenarios means you "handled" the promise rejection correctly.
2. Database validation - Path 'name' is required.. This literally means that you have a required path called "name" which is required (meaning, it must have a value). So looking at your code it's pretty obvious:
const skill = new Skill({});
skill.save() //-> results in error
This is fixed by adding all required data before saving:
const skill = new Skill({ name: "Jason" });
skill.save() //-> yay, no error
You're not handling the promise rejection.
Change this:
.then((err, product, numAffected) => {
console.log("Error: ", err);
});
to this:
.then((result) => {
console.log('Result:', result);
}).catch((error) => {
console.log('Error:', error);
Of course change what happens in the callbacks to whatever you need.
See this answer for more general info on unhandled rejection:
Should I refrain from handling Promise rejection asynchronously?

Resources