I am trying to create a mean app. I am receiving errors while connecting mean app with MongoDb using mongoose. I am using "express": "^4.17.1", and "mongoose": "^6.0.7".
const mongoose = require('mongoose');
// Connecting to MongoDb
mongoose.connect(
'mongodb+srv://MongoDb:<password>#cluster0.xfdie.mongodb.net/myFirstDatabase?retryWrites=true&w=majority',
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
// On Connection
mongoose.connection.on('connected', () => {
console.log('Connected to MongoDb');
});
mongoose.connection.on('error', (err) => {
if (err) {
console.log('Error in MongoDb Connection' + err);
}
});
It's working fine with the localhost but I am receiving the following error in Stackblitz.
Error in MongoDb ConnectionTypeError: this._handle[e] is not a function
(node:13) UnhandledPromiseRejectionWarning: TypeError: this._handle[e] is not a function
at Resolver.querySrv [as resolveSrv] (https://file-sharing-portal.jw.staticblitz.com/blitz.fa2fa735bbb029186c23972eb56445ed5c5fdef5.js:6:585119)
at Object.resolveSRVRecord (/home/projects/file-sharing-portal/node_modules/mongodb/lib/connection_string.js:55:9)
at Object.connect (/home/projects/file-sharing-portal/node_modules/mongodb/lib/operations/connect.js:41:36)
at eval (/home/projects/file-sharing-portal/node_modules/mongodb/lib/mongo_client.js:127:23)
at Object.maybePromise (/home/projects/file-sharing-portal/node_modules/mongodb/lib/utils.js:518:5)
at MongoClient.connect (/home/projects/file-sharing-portal/node_modules/mongodb/lib/mongo_client.js:126:24)
at eval (/home/projects/file-sharing-portal/node_modules/mongoose/lib/connection.js:785:12)
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (/home/projects/file-sharing-portal/node_modules/mongoose/lib/connection.js:776:19)
at eval (/home/projects/file-sharing-portal/node_modules/mongoose/lib/index.js:328:10)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:13) 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:13) [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.
Please assist.
I asked for help in stackblitz-help channel in discord for the same and was informed that Mongoose isn't supported yet : https://github.com/stackblitz/core/issues/251
const mongoose = require('mongoose');
const app = express();
mongoose.Promise = global.Promise;
mongoose.connect("CONNECTION_STRING", "OPTIONS", (error) => {
if (error)
console.log("Connection error - ", error);
else
console.log("MongoDB connection established");
});
let server = http.createServer(app);
server.setTimeout(500000);
server.listen(3000);
try with above code snippets
Related
i want to send the updatedUser informations plus an image file in the response but I get this kind of error: " 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:69044) [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.".i googled this error but nothing helpful, so this is my code :
userRouter.post("/upload/:id",async(req, res)=> {
const user_id = req.params.id;
const pp = req.files.productImage;
const {data} = pp;
const namePp = uuidv4() + '.' + pp.name.split('.').pop();
pp.mv("./picturesProfile/" + namePp);
const updatedUser = await User.findByIdAndUpdate(user_id, {new: true},{image: namePp}, function (err, docs) {
if(err) {
console.log(err)
} else {
return docs
}
})
console.log(updatedUser)
res.send({updatedUser,pp});
})
This one will work you!
const doc = await User.findByIdAndUpdate(user_id,
{ $set: { "image": namePp }},
{
new: true,
runValidators : true
});
UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND api.sendgrid.com api.sendgrid.com:443
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
(node:6768) 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:6768) [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.
Please could you be more elaborate or better still add code snippet of your code for clearer understanding.
But from what I'm suspecting, I think there is an asynchronous call that you made that was not handled properly which might be that you didn't catch an error exception after the call.
Always remember that transport.sednmail() is an asynchronous function and it returns a promise.
See example below:
// With ".then" function
transport.sendMail(email)
.then(response => console.log(response))
.catch(error => console.log(error))
// With Callback function
transport.sendMail(email, (error, response) => {
if(error) {
console.log(error);
}
else{
console.log(response);
}
})
I hope this might be of little help to fixing the issue.
I'm following this tutorial to setup the mongo atlas db.
https://developerhandbook.com/mongodb/connect-mongo-atlas-mongoose/
But on the setup of connection, I got error like
(node:60566) UnhandledPromiseRejectionWarning: MongoError: user is not allowed to do action [find] on [admin.sample_airbnb]
at queryCallback (/Users/jay.lin/dev/graphql-playlist/server/node_modules/mongodb-core/lib/cursor.js:223:25)
at /Users/jay.lin/dev/graphql-playlist/server/node_modules/mongodb-core/lib/connection/pool.js:541:18
at process._tickCallback (internal/process/next_tick.js:61:11)
(node:60566) 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:60566) [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.
It seems atlas db is using "admin" collection by default, how can I change it to "sample_airbnb" collection?
const connector = mongoose.connect(
'mongodb+srv://test:<password>#cluster0-ppeaz.mongodb.net/a?retryWrites=true&w=majority'
)
.then(() => {
// connector.useDb('sample_airbnb?');
const Listing = mongoose.model(
'listingsAndReviews',
new mongoose.Schema({
name: String,
summary: String,
}),
'sample_airbnb'
);
Listing.findOne({}).then((r) => {
console.log(r);
})
})
(node:60566) You need to add "admin permission"s to be able to query the db. This will be under "security" tab then "Database Access". "Add new user" button (which is then used in your connection string).
".mongodb.net/a?" needs to be ".mongodb.net/sample_airbnb?"
(node:60566) Use try catch e.g.
const connector = mongoose.connect(
'mongodb+srv://test:<password>#cluster0-ppeaz.mongodb.net/sample_airbnb?retryWrites=true&w=majority'
)
.then(() => {
// connector.useDb('sample_airbnb?');
const Listing = mongoose.model(
'listingsAndReviews',
new mongoose.Schema({
name: String,
summary: String,
}),
'sample_airbnb'
);
try {
const listings = await Listing.findOne({});
res.json(listings);
} catch (err) {
res.json({ message: err });
}
});
});
I want to connect my express app to my mongoDb Atlas cluster.I'm from Iran, and cloud databases are sanctioned for us. I used VPN to bypass it in order to be able to practice.
Is there some coding mistake that I've done or is it because of using VPN?
The error:
(node:9008) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
connected
events.js:174
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND
is listening...
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
Emitted 'error' event at:
at GetAddrInfoReqWrap.doListen [as callback] (net.js:1448:12)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:17)
[nodemon] app crashed - waiting for file changes before starting...
And the code:
database.js
----------------
const mongoDb = require('mongodb');
const MongoClient = mongoDb.MongoClient;
let _db;
const mongoConnect = callback => {
MongoClient.connect(
'mongodb+srv://<someUser>:<somePassword>#<someCluster>-zh1eb.mongodb.net/test?retryWrites=true'
)
.then(client => {
console.log('\nconnected\n');
_db = client.db();
callback();
})
.catch(err => {
console.log('\nerror\n', err);
throw err;
});
};
const getDb = () => {
if (_db) {
return _db;
}
throw 'NO DATABASE FOUND';
};
exports.mongoConnect = mongoConnect;
exports.getDb = getDb;
app.js
------------
...
const mongoConnect = require('./util/database').mongoConnect;
...
mongoConnect(() => {
app.listen(3000, '\nis listening...\n');
});
I found out what was the problem:
mongoConnect(() => {
app.listen(3000, '\nis listening...\n');
});
should actually be
mongoConnect(() => {
app.listen(3000, () => { console.log('\nis listening...\n');});
});
Silly me... :)
For those having such issue:
first check out whether the source of problem is your code or the connection to MongoDb.
That is instead of choosing "connect your application" select "connect with Mongodb Compass".
If the Mongodb Compass could connect and show your cluster, then definitely there is something wrong with your code, esp. how it's coded to connect.
This is my code:
db.Registration.model.countDocuments()
.then(function (count) {
return res.status(200).send({ count });
})
.catch(function (err) {
console.log('errrr', err);
if (err)
return res.status(500).sendStatus(err);
else
return res.status(200).sendStatus({ count });
})
I get the following error:
Express server running on *:5000
(node:8864) UnhandledPromiseRejectionWarning: Error: querySrv ENOTFOUND _mongodb._tcp.cluster0-shard-00-00-jjbdh.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19)
(node:8864) 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:8864) [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.
Why catch is not working and I get this error instead?