Cesar
Cesar5mo ago

Error connecting to mongoose when using deno cli

deno-x86_64-pc-windows-msvc v1.41.1 Testing the following code using nodejs and on deno deploy works correctly:
import express from 'express';
import mongoose from 'mongoose';

const app = express();
await mongoose.connect("mongodb+srv://...");
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('Connected to MongoDB');
});

app.listen(3001, () => { console.log('starting...'); });
import express from 'express';
import mongoose from 'mongoose';

const app = express();
await mongoose.connect("mongodb+srv://...");
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('Connected to MongoDB');
});

app.listen(3001, () => { console.log('starting...'); });
But when testing using deno cli it doesn't work. I get the message on the console starting... but not the connection error: neither Connected to MongoDB And after some time I get this error:
error: Uncaught (in promise) MongooseServerSelectionError: connection timed out
at _handleConnectionErrors (file:///.../node_modules/.deno/mongoose@8.2.1/node_modules/mongoose/lib/connection.js:875:11)
error: Uncaught (in promise) MongooseServerSelectionError: connection timed out
at _handleConnectionErrors (file:///.../node_modules/.deno/mongoose@8.2.1/node_modules/mongoose/lib/connection.js:875:11)
The same thing happens using mongodb instead of mongoose:
import express from 'express';
import mongodb from 'mongodb';

const app = express();
const client = new mongodb.MongoClient("mongodb+srv://...")
await client.connect();
const db = client.db();

app.listen(3001, () => { console.log('starting...'); });
import express from 'express';
import mongodb from 'mongodb';

const app = express();
const client = new mongodb.MongoClient("mongodb+srv://...")
await client.connect();
const db = client.db();

app.listen(3001, () => { console.log('starting...'); });
C:\Windows\system32>deno run --allow-all ...\index.js
Warning: Not implemented: ClientRequest.options.createConnection
error: Uncaught (in promise) MongoServerSelectionError: connection timed out
at AbortSignal.<anonymous> (file:///...node_modules/.deno/mongodb@6.4.0/node_modules/mongodb/lib/sdam/topology.js:292:34)
C:\Windows\system32>deno run --allow-all ...\index.js
Warning: Not implemented: ClientRequest.options.createConnection
error: Uncaught (in promise) MongoServerSelectionError: connection timed out
at AbortSignal.<anonymous> (file:///...node_modules/.deno/mongodb@6.4.0/node_modules/mongodb/lib/sdam/topology.js:292:34)
I'm starting the script as
deno run --allow-all ...\index.js
deno run --allow-all ...\index.js
I also tested running it as admin, on the Mongo website I have all ip whitelisted Why do I get this error only on the CLI version?
56 Replies
Deno AI Helper
Deno AI Helper5mo ago
When working with MongoDB in Deno, the documentation suggests using the official MongoDB driver with npm specifiers. This means that instead of using Mongoose, which is a higher-level abstraction built for Node.js, you should use the MongoDB driver directly. Here's an example from the documentation on how to connect to MongoDB using the MongoDB driver in Deno:
import { MongoClient } from "npm:mongodb@6.1.0";

const client = new MongoClient("mongodb://127.0.0.1:27017");
await client.connect();
console.log("Connected successfully to server");

const db = client.db("myProject");
const collection = db.collection("documents");

const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }]);
console.log("Inserted documents =>", insertResult);

client.close();
import { MongoClient } from "npm:mongodb@6.1.0";

const client = new MongoClient("mongodb://127.0.0.1:27017");
await client.connect();
console.log("Connected successfully to server");

const db = client.db("myProject");
const collection = db.collection("documents");

const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }]);
console.log("Inserted documents =>", insertResult);

client.close();
To run this example, you would use the Deno CLI with the appropriate permissions:
deno run --allow-net --allow-sys --allow-read your_script.ts
deno run --allow-net --allow-sys --allow-read your_script.ts
The error you're encountering with Mongoose may be due to compatibility issues since Mongoose is designed to work with Node.js and not directly with Deno. Deno has a different runtime environment and module resolution system, which could lead to unexpected behavior when trying to use Node.js-specific packages like Mongoose. To resolve your issue, consider using the MongoDB driver directly as shown in the documentation example. Make sure to replace the connection string with your actual MongoDB URI and adjust the database and collection names as needed. If you need to use Mongoose for some reason, you might want to check if there's an updated version or a Deno-specific fork that is compatible with Deno's runtime. However, based on the documentation, the recommended approach is to use the MongoDB driver with npm specifiers. 🦕
Cesar
Cesar5mo ago
is someone else able to reproduce this issue?
lexand
lexand5mo ago
https://docs.deno.com/runtime/tutorials/how_to_with_npm/mongoose Did you follow this tutorial? Seems like there is something with your import maybe?
How to use Mongoose with Deno | Deno Docs
Mongoose is a popular, schema-based library that
Cesar
Cesar5mo ago
its fails even with Mongodb and the same code works on deno deploy/ local nodejs
lexand
lexand5mo ago
do you use 'npm:mongoose...' in your deno file?
Cesar
Cesar5mo ago
no i have the npm imports in deno.json
lexand
lexand5mo ago
oh ok, i never used like this, maybe try with this : import { model, Schema } from "npm:mongoose@^6.7"; import mongoose from "npm:mongoose@^6.7";
Cesar
Cesar5mo ago
it doesnt work either, getting similar error, does it work at your side?
import { MongoClient } from "npm:mongodb@6.1.0";

const client = new MongoClient("mongodb+srv://...");
await client.connect();
console.log("Connected successfully to server");
import { MongoClient } from "npm:mongodb@6.1.0";

const client = new MongoClient("mongodb+srv://...");
await client.connect();
console.log("Connected successfully to server");
C:\Users\CAIO\Documents\NodejsConsoleApp1>deno run --allow-all app.js
error: Uncaught (in promise) MongoServerSelectionError: connection timed out
at Timeout._onTimeout (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongodb@6.1.0/node_modules/mongodb/lib/sdam/topology.js:278:38)
at cb (ext:deno_node/internal/timers.mjs:63:31)
at Object.action (ext:deno_web/02_timers.js:154:11)
at handleTimerMacrotask (ext:deno_web/02_timers.js:68:10)
at eventLoopTick (ext:core/01_core.js:173:21)
Caused by: MongoNetworkTimeoutError: connection timed out
at connectionFailureError (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongodb@6.1.0/node_modules/mongodb/lib/cmap/connect.js:381:20)
at TLSSocket.<anonymous> (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongodb@6.1.0/node_modules/mongodb/lib/cmap/connect.js:285:22)
at Object.onceWrapper (ext:deno_node/_stream.mjs:1929:32)
at TLSSocket.emit (ext:deno_node/_stream.mjs:1854:9)
at TLSSocket._onTimeout (node:net:848:10)
at cb (ext:deno_node/internal/timers.mjs:63:31)
at Object.action (ext:deno_web/02_timers.js:154:11)
at handleTimerMacrotask (ext:deno_web/02_timers.js:68:10)
at eventLoopTick (ext:core/01_core.js:173:21)
C:\Users\CAIO\Documents\NodejsConsoleApp1>deno run --allow-all app.js
error: Uncaught (in promise) MongoServerSelectionError: connection timed out
at Timeout._onTimeout (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongodb@6.1.0/node_modules/mongodb/lib/sdam/topology.js:278:38)
at cb (ext:deno_node/internal/timers.mjs:63:31)
at Object.action (ext:deno_web/02_timers.js:154:11)
at handleTimerMacrotask (ext:deno_web/02_timers.js:68:10)
at eventLoopTick (ext:core/01_core.js:173:21)
Caused by: MongoNetworkTimeoutError: connection timed out
at connectionFailureError (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongodb@6.1.0/node_modules/mongodb/lib/cmap/connect.js:381:20)
at TLSSocket.<anonymous> (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongodb@6.1.0/node_modules/mongodb/lib/cmap/connect.js:285:22)
at Object.onceWrapper (ext:deno_node/_stream.mjs:1929:32)
at TLSSocket.emit (ext:deno_node/_stream.mjs:1854:9)
at TLSSocket._onTimeout (node:net:848:10)
at cb (ext:deno_node/internal/timers.mjs:63:31)
at Object.action (ext:deno_web/02_timers.js:154:11)
at handleTimerMacrotask (ext:deno_web/02_timers.js:68:10)
at eventLoopTick (ext:core/01_core.js:173:21)
lexand
lexand5mo ago
import mongoose from "npm:mongoose@^6.7";

async function main(){
await mongoose.connect("mongodb+srv://***/?retryWrites=true&w=majority&appName=Test")
}

main()
.then(()=>console.log('connecte'))
.catch(err=> console.log(err));``
import mongoose from "npm:mongoose@^6.7";

async function main(){
await mongoose.connect("mongodb+srv://***/?retryWrites=true&w=majority&appName=Test")
}

main()
.then(()=>console.log('connecte'))
.catch(err=> console.log(err));``
and it works. i did in the past get the same error, probably user/password incorrectlly, i don't know but that's how i did
Cesar
Cesar5mo ago
i tried your code it also throws a connection timed out error
'use strict';

import mongoose from "npm:mongoose@^6.7";

async function main(){
await mongoose.connect("mongodb+srv://...@....mongodb.net/...?retryWrites=true&w=majority")
}

main()
.then(()=>console.log('connecte'))
.catch(err=> console.log(err));
'use strict';

import mongoose from "npm:mongoose@^6.7";

async function main(){
await mongoose.connect("mongodb+srv://...@....mongodb.net/...?retryWrites=true&w=majority")
}

main()
.then(()=>console.log('connecte'))
.catch(err=> console.log(err));
C:\Users\CAIO\Documents\NodejsConsoleApp1>deno run --allow-net --allow-sys --allow-read app.js
:white_check_mark: Granted all env access.
MongooseServerSelectionError: connection timed out
at NativeConnection.Connection.openUri (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongoose@6.12.7/node_modules/mongoose/lib/connection.js:825:32)
at file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongoose@6.12.7/node_modules/mongoose/lib/index.js:414:10
at file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongoose@6.12.7/node_modules/mongoose/lib/helpers/promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongoose@6.12.7/node_modules/mongoose/lib/helpers/promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongoose@6.12.7/node_modules/mongoose/lib/index.js:1290:10)
at Mongoose.connect (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongoose@6.12.7/node_modules/mongoose/lib/index.js:413:20)
at main (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/app.js:6:20)
at file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/app.js:9:1 {
message: "connection timed out",
C:\Users\CAIO\Documents\NodejsConsoleApp1>deno run --allow-net --allow-sys --allow-read app.js
:white_check_mark: Granted all env access.
MongooseServerSelectionError: connection timed out
at NativeConnection.Connection.openUri (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongoose@6.12.7/node_modules/mongoose/lib/connection.js:825:32)
at file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongoose@6.12.7/node_modules/mongoose/lib/index.js:414:10
at file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongoose@6.12.7/node_modules/mongoose/lib/helpers/promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongoose@6.12.7/node_modules/mongoose/lib/helpers/promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongoose@6.12.7/node_modules/mongoose/lib/index.js:1290:10)
at Mongoose.connect (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/node_modules/.deno/mongoose@6.12.7/node_modules/mongoose/lib/index.js:413:20)
at main (file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/app.js:6:20)
at file:///C:/Users/CAIO/Documents/NodejsConsoleApp1/app.js:9:1 {
message: "connection timed out",
how you are starting your script, is it ts or js? i even tried creating a new mongo db same error
lexand
lexand5mo ago
deno run -A --watch main.ts Deno need permission, this command should work, i hope
Cesar
Cesar5mo ago
could you try with a js project?
lexand
lexand5mo ago
oh ok, sorry i didn't read fully the error prompt
Cesar
Cesar5mo ago
No description
lexand
lexand5mo ago
i tried the same project with node and deno
Cesar
Cesar5mo ago
do i need something else? looks like its stopped after that watcher message ah it started now
MongooseServerSelectionError: connection timed out
MongooseServerSelectionError: connection timed out
same thing :/ on node works perfect
lexand
lexand5mo ago
hm strange indeed i don't know what to say beside, work on node ? x)
mongoose.connect(uri, {
serverSelectionTimeoutMS: 5000
});
mongoose.connect(uri, {
serverSelectionTimeoutMS: 5000
});
` Try to use this parameter with a higher value
Cesar
Cesar5mo ago
does your test project contain any other file other than the index.js?
lexand
lexand5mo ago
no i just tried to connect to Mongo Atlas
Cesar
Cesar5mo ago
i mean if the cli require you to configure something different like the npm: thing
lexand
lexand5mo ago
I use VS Code with the Deno extension. I just had to cache the npm:mongoose thingy and that's all
Cesar
Cesar5mo ago
i hate vscode, ill try with it
lexand
lexand5mo ago
what do you use then?
Cesar
Cesar5mo ago
visual studio
lexand
lexand5mo ago
oh i see, well, i don't know how it works on Visual Studio but i highly recommend to use VS Code. Or you willl have to use the CLI often
Cesar
Cesar5mo ago
same error
No description
lexand
lexand5mo ago
try to add the serverSelectionTimeoutMS with 10 second, maybe it need more time? , { serverSelectionTimeoutMS: 10000 }
Cesar
Cesar5mo ago
i tried now, same thing :/
lexand
lexand5mo ago
hm well i don't know, but at least it works on node which is better than nothing x)
Cesar
Cesar5mo ago
No description
Cesar
Cesar5mo ago
yes on node works correctly deno is pissing me off
lexand
lexand5mo ago
i don't really know why it doesn't work but the documentation says it's better to use the mongodb driver and not mongoose
Cesar
Cesar5mo ago
it also doesnt work with mongodb
lexand
lexand5mo ago
i will try with mongodb on deno
Cesar
Cesar5mo ago
could you try with js instead of ts
lexand
lexand5mo ago
sure
import { MongoClient } from "npm:mongodb@6";

const client = new MongoClient('mongodb+srv://');
client.connect()
.then(()=>console.log('connecte'))
.catch((err)=>console.log(err));
import { MongoClient } from "npm:mongodb@6";

const client = new MongoClient('mongodb+srv://');
client.connect()
.then(()=>console.log('connecte'))
.catch((err)=>console.log(err));
` const client = new MongoClient('***',{ connectTimeoutMS:5000, }); we never know
Cesar
Cesar5mo ago
worked?
lexand
lexand5mo ago
yup for me
Cesar
Cesar5mo ago
whats your deno cli version and your os
lexand
lexand5mo ago
deno : 1.41.1 windows 10
Cesar
Cesar5mo ago
same here
lexand
lexand5mo ago
you could always install MongoCompass on your computer and connect to it
Cesar
Cesar5mo ago
i already have it
lexand
lexand5mo ago
oh ok
Cesar
Cesar5mo ago
im connecting to it, not locally
lexand
lexand5mo ago
you use MongoCompass to connect to MongoAtlas?
Cesar
Cesar5mo ago
no, i mean that i'm not connecting to a local db
lexand
lexand5mo ago
i update to deno 1.41.2 (with deno upgrade) and change npm:mongodb@6.4.0 It works too
Cesar
Cesar5mo ago
im getting ISOLATE_INTERNAL_FAILURE on deno deplo , i was trying to use deno cli to debug it: https://discord.com/channels/684898665143206084/826085979344470037/1215689372305723444 I'm thinking of switching to Heroku, already wasted a lot of time with
lexand
lexand5mo ago
your entrypoint is your server file? if you are ready to pay x) i think there is another option for free hosting
Cesar
Cesar5mo ago
wdym? paying is not a problem
lexand
lexand5mo ago
deployctl deploy --project=helloworld --entrypoint=src/entrypoint.ts => should point to your server file
Cesar
Cesar5mo ago
im using the website not the deployctl my entrypoint is the index.js
lexand
lexand5mo ago
ok, i never used a git repo to deploy on deno deploy, my bad try using deno deploy ctl, maybe it'll work? who knows
Cesar
Cesar5mo ago
i dont know how to use it, ill read about
lexand
lexand5mo ago
https://docs.deno.com/deploy/manual/deployctl there you go if you need informations
Using deployctl on the command line | Deno Docs
deployctl is a command line tool (CLI) that lets you work with the Deno Deploy
More Posts
How to debug deno on Visual Studio? (Not VSCode)Is it possible to debug deno on Visual Studio? (not vscode) I only know how to debug it using windoHow to polyfill node imports when bundling with the deno version of esbuild?Hello, I am trying to run esbuild using https://deno.land/x/esbuild to bundle a Deno project into aforward stream response from openapi to frontendforward stream openapi by using deno backend as a middleware, how to receive and send stream to fronShould deno install work with jsr?What am I doing wrong? When I try to install a CLI from jsr.io and then use it, I get an error messaImport-IntelliSense with Fresh and VSCode doesn't work as expectedHey. I'm fairly new to Deno and Fresh so I assume I'm simply missing something. I've created a FreshHow to rewrite this code so I don't have to force deno to stop linting?```ts import { parse } from "https://deno.land/std@0.218.2/toml/mod.ts"; import { match } from "npm:Deno compile optimizationHi Everyone, I'm building a CLI tool with Deno and I was wondering - if there are any optimizationIs there a way to select Partial Mode on button?I researched and I do not think it is possible, but it would be nice to do something like: ```<a f-pHow to Restart Server ManuallyI run Hono framework with Deno. I run the server using task script `deno run -A --watch ./server/maiIs there any reference manual for how doc comments are rendered on JSR or deno.land/x?I guessed it's just TSDoc, but it turns out that it's not exactly TSDoc (e.g., `@link` to an instanc