ReferenceError: TextEncoder is not defined Node.js with mongoose
Asked Answered
I

5

9

the problem seems to be with mongoose & mongodb packages as it works fine when

mongoose.connect('mongodb+srv://mydb:<password>@cluster0.w1opr.mongodb.net/test?retryWrites=true&w=majority');

is removed it also works fine on repl.it cloud env here is my code

var express = require('express');
var ejs = require('ejs');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb+srv://mydb:<password>@cluster0.w1opr.mongodb.net/test? 
retryWrites=true&w=majority');
app.set('view engine','ejs')
app.use(bodyParser.urlencoded({extended: true}));
.
.
.
app.listen(3000,function(){
console.log('Server is running on port 3000');
});
Improvisatory answered 1/9, 2021 at 14:35 Comment(0)
Q
35

Actually mongoose 6 requires Node 12 or higher, so this is expected behavior. Mongoose 6 does not support Node 10.So updating Node version will fix the issue. It also fix the problem by downgrading mongoose version to 5.

Quotation answered 8/9, 2021 at 6:42 Comment(3)
I am using Node 14 and still go this error.Mound
Using node 16 and the error persists.Pemmican
getting this error with node version 18 tooExpense
B
8

Had the same problem when using tests. Setting the testEnvironment to node in my jest config fixed it (https://mongoosejs.com/docs/jest.html)

module.exports = {
  testEnvironment: 'node'
};
Borroff answered 20/12, 2022 at 13:50 Comment(0)
H
5

Check your node version, if it's lower than 12 it won't work, if that's the case updating node should do do the job. You could downgrade your mongoose version too.

There's an issue closed on Mongoose github page. https://github.com/Automattic/mongoose/issues/10638

Hallett answered 3/9, 2021 at 4:51 Comment(0)
C
5

To get rid of this error in Windows upgrade to the latest version of Node.js by visiting this site https://nodejs.org/en/download/ and downloading the latest version of Node.js else if you do not want to upgrade to the latest version then you can get rid of this error by adding this line at the top of the file in node_modules/whatwg-url/dist/encoding.js:

const {TextDecoder, TextEncoder} = require("util");
Cothurnus answered 28/10, 2021 at 7:29 Comment(0)
C
0

For me i'm using UBUNUTU 20.04, as @MuhammadTariq said my node version was 10 and after upgrading the version to 16 the error is gone.

Crop answered 31/3, 2022 at 4:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.