D
Deno

help

Error connecting to mongoose when using deno cli

CCesar3/6/2024
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?
DAHDeno AI Helper3/6/2024
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. 🦕
CCesar3/6/2024
is someone else able to reproduce this issue?
Llexand3/8/2024
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
CCesar3/8/2024
its fails even with Mongodb and the same code works on deno deploy/ local nodejs
Llexand3/8/2024
do you use 'npm:mongoose...' in your deno file?
CCesar3/8/2024
no i have the npm imports in deno.json
Llexand3/8/2024
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";
CCesar3/8/2024
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)
Llexand3/8/2024
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
CCesar3/8/2024
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
Llexand3/8/2024
deno run -A --watch main.ts Deno need permission, this command should work, i hope
CCesar3/8/2024
could you try with a js project?
Llexand3/8/2024
oh ok, sorry i didn't read fully the error prompt
CCesar3/8/2024
No description
Llexand3/8/2024
i tried the same project with node and deno
CCesar3/8/2024
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
Llexand3/8/2024
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
CCesar3/8/2024
does your test project contain any other file other than the index.js?
Llexand3/8/2024
no i just tried to connect to Mongo Atlas
CCesar3/8/2024
i mean if the cli require you to configure something different like the npm: thing
Llexand3/8/2024
I use VS Code with the Deno extension. I just had to cache the npm:mongoose thingy and that's all
CCesar3/8/2024
i hate vscode, ill try with it
Llexand3/8/2024
what do you use then?
CCesar3/8/2024
visual studio
Llexand3/8/2024
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
CCesar3/8/2024
same error
No description
Llexand3/8/2024
try to add the serverSelectionTimeoutMS with 10 second, maybe it need more time? , { serverSelectionTimeoutMS: 10000 }
CCesar3/8/2024
i tried now, same thing :/
Llexand3/8/2024
hm well i don't know, but at least it works on node which is better than nothing x)
CCesar3/8/2024
No description
CCesar3/8/2024
yes on node works correctly deno is pissing me off
Llexand3/8/2024
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
CCesar3/9/2024
it also doesnt work with mongodb
Llexand3/9/2024
i will try with mongodb on deno
CCesar3/9/2024
could you try with js instead of ts
Llexand3/9/2024
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
CCesar3/9/2024
worked?
Llexand3/9/2024
yup for me
CCesar3/9/2024
whats your deno cli version and your os
Llexand3/9/2024
deno : 1.41.1 windows 10
CCesar3/9/2024
same here
Llexand3/9/2024
you could always install MongoCompass on your computer and connect to it
CCesar3/9/2024
i already have it
Llexand3/9/2024
oh ok
CCesar3/9/2024
im connecting to it, not locally
Llexand3/9/2024
you use MongoCompass to connect to MongoAtlas?
CCesar3/9/2024
no, i mean that i'm not connecting to a local db
Llexand3/9/2024
i update to deno 1.41.2 (with deno upgrade) and change npm:mongodb@6.4.0 It works too
CCesar3/9/2024
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
Llexand3/9/2024
your entrypoint is your server file? if you are ready to pay x) i think there is another option for free hosting
CCesar3/9/2024
wdym? paying is not a problem
Llexand3/9/2024
deployctl deploy --project=helloworld --entrypoint=src/entrypoint.ts => should point to your server file
CCesar3/9/2024
im using the website not the deployctl my entrypoint is the index.js
Llexand3/9/2024
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
CCesar3/9/2024
i dont know how to use it, ill read about
Llexand3/9/2024
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

Looking for more? Join the community!

Recommended 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 instancHow to start using data validation in kv?Hey fellows! I want to dive into data validation. Any experience or suggestions? Feel free to postdeno cache isn't working from vscodeWhen initializing a new fresh project from the cli script `deno run -A -r https://fresh.deno.dev` an`.read()` method in `Deno.Conn` or `Deno.FsFile` in Deno 2.0After `Deno.Reader` is removed in v2.0, will we still be able to use `.read()` method in `Deno.Conn`Stuck trying to install a JSR package with its dependencies and use it in a browserI published https://jsr.io/@datasette/table to JSR - an experimental web component package - and nowList of available demo commandsIs there a programmatic way to get a list of all possible deno commands? Something like: ```ts consServer isolates cause Socket.IO problemsHi guys, I have a simple socket.IO program that basically broadcasts the changes in any one client'Puppeteer: "BadResource: Bad resource ID" on UbuntuHello, i just switched my server os over to ubuntu server 23.10. When executing my script, it immediUnable to use Deno.createHttpClient without deprecated flag --unstableI expected it to be behind the newer `--unstable-net` flagMultiple JsRuntimes crashe if first is not dropped before a second is created and ranIn my application, I want an `op2` to take in a function which will be stored in a struct as a `GlobStructure microservicesHi, how would you structure a Deno microservice repository with a good developer experience (good d