46

I am just making a database called Fruits from my app.js and connecting the database to MongoDB using Mongoose.

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true});

mongoose.set('strictQuery', false);

const fruitSchema = new mongoose.Schema({
    name: String,
    rating: Number,
    review: String
});

const Fruit = mongoose.model("Fruit", fruitSchema);

const fruit = new Fruit({
    name: "Apple",
    rating: 7,
    review: "Taste Good"
});

fruit.save();

Whenever I try node app.js, I am getting DeprecationWarning. Even though I tried using mongoose.set('strictQuery', true);, the same error continues as follows:

(node:15848) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option w
ill be switched back to `false` by default in Mongoose 7. Use `mongoose.set('str
ictQuery', false);` if you want to prepare for this change. Or use `mongoose.set
('strictQuery', true);` to suppress this warning.
(Use `node --trace-deprecation ...` to show where the warning was created)
D:\Web Development\FruitsProject\node_modules\mongoose\lib\drivers\node-mongodb-
native\collection.js:158
          const err = new MongooseError(message);
                      ^

MongooseError: Operation `fruits.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (D:\Web Development\FruitsProject\node_modules\mongoo
se\lib\drivers\node-mongodb-native\collection.js:158:23)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7)

Node.js v18.12.1

And then the second error also continues fruits.insertOne().

Because of this, my MongoDB database is not getting updated.

test> show dbs
admin    40.00 KiB
config  108.00 KiB
local    40.00 KiB
shopDB   72.00 KiB

I just want to fix this error. But I don't know where to fix this error. For the second part of the error, it seems like it is coming from the node_modules itself. How can I fix this error?

Rahul Saran
  • 467
  • 1
  • 3
  • 8
  • please understand the actual problem before going to the solution, 1. put your code in try catch and check what is the error, in my case I defined the constraints and I was adding the data that's why it provided the errors so I just changed my constraint and it worked moral of the Comment :: if we strictly put the data what might the violation of any constraints – Haseeb Ullah Dec 22 '22 at 12:29
  • 1
    const fruitSchema = new mongoose.Schema({ name: String, rating: Number, review: String }); please Change it to const fruitSchema = new mongoose.Schema({ name: {type: String}, rating:{type: Number} , review: {type: String} }); it won't give any error – Haseeb Ullah Dec 22 '22 at 12:32
  • Re *"nodule_modules"*: Don't you mean *[node_modules](https://stackoverflow.com/questions/63294260/what-is-the-purpose-of-the-node-modules-folder)?* (the folder named "`node_modules`") – Peter Mortensen Feb 16 '23 at 22:35
  • Allegedly, it is [from a Udemy course](https://stackoverflow.com/questions/74747476/deprecationwarning-mongoose-the-strictquery-option-will-be-switched-back-to/74783773#74783773). – Peter Mortensen Feb 16 '23 at 23:06

23 Answers23

82
mongoose.set("strictQuery", false);

mongoose.connect(process.env.MONGO_URL);

OR

mongoose.set("strictQuery", false);
mongoose.connect(process.env.MONGO_URL, () => {
  console.log("Connected to MongoDB");
});
const connectDB = async () => {
    try {
        mongoose.set('strictQuery', false);
        await mongoose.connect(db, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        console.log('MongoDB Connected...');
    } catch (err) {
        console.error(err.message);
        // make the process fail
        process.exit(1);
    }
ZebraCoder
  • 1,480
  • 1
  • 5
  • 12
33

I want to give a little more context to existing answers.

When the strict option is set to true, Mongoose will ensure that only the fields that are specified in your schema will be saved in the database, and all other fields will not be saved (if some other fields are sent).

Right now, this option is enabled by default, but it will be changed in Mongoose v7 to false by default. That means that all the fields will be saved in the database, even if some of them are not specified in the schema model.


So, if you want to have strict schemas and store in the database only what is specified in you model, starting with Mongoose v7, you will have to set strict option to true manually.

mongoose.set('strictQuery', true);
mongoose.connect(Config.mongo_db_connection_string);

If you don't want this, you don't have to specify anything, since it will be set to false by default. So, you can just connect to the database and that's it.

mongoose.connect(Config.mongo_db_connection_string);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
NeNaD
  • 18,172
  • 8
  • 47
  • 89
  • 5
    strict Schema is different than the strictQuery option. As outlined in the mongoose documentation here: https://mongoosejs.com/docs/guide.html#strict . The Schema strict option is enabled by default and can be changed on the Schema level, also the default behavior is not changing in version 7 of mongoose. The strictQuery option which can be set globally as you have outlined will be set be set to false in mongoose 7. https://mongoosejs.com/docs/guide.html#strictQuery: The strictQuery option is just for query filters. – toinhao Jan 09 '23 at 08:37
5
const mongoose = require("mongoose");

mongoose.set('strictQuery', false);
mongoose.connect("mongodb://localhost:27017/fruitsDB", { useNewUrlParser: true });

const fruitSchema = new mongoose.Schema({
  name: String,
  rating: Number,
  review: String
});

const Fruit = mongoose.model("Fruit", fruitSchema);

const fruit = new Fruit({
    name: "Apple",
    rating: 7,
    review: "Taste Good"
});

fruit.save();
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • we should use the given line first then mongoose. Connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true}); mongoose. Set('strictQuery', false); – MATI UL REHMAN Dec 16 '22 at 18:33
  • 3
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Dec 19 '22 at 16:10
4

This warning message is indicating that the Mongoose library is currently using the "strictQuery" option and that this option will be switched back to "false" in Mongoose 7 by default. Mongoose uses this option to determine whether to enforce strict query syntax. When set to "false", Mongoose will allow query conditions to match multiple properties.

To resolve this warning, you can either set "strictQuery" to "false" in your code by using the following line:

mongoose.set('strictQuery', false);

Or, if you want to continue using strict query syntax, you can suppress this warning by setting "strictQuery" to "true":

mongoose.set('strictQuery', true);

It's recommended to update your code in accordance with this change before Mongoose 7 is released.

Example:

const mongoose = require("mongoose");

mongoose.set('strictQuery', false);

mongoose.connect("mongodb://localhost:27017/test", {
    useNewUrlParser: true
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Suresh B
  • 379
  • 4
  • 3
3

Remove this warning with just one line

mongoose.set('strictQuery', true);
mongoose.connect(process.env.MONGO_URL)
Rahul Saran
  • 467
  • 1
  • 3
  • 8
Patwal
  • 31
  • 2
3

Solution for the first error

You can refer to the command line instruction itself. Just use the suggested line before using Mongoose.

Simply replace:

mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true});

To:

mongoose.set('strictQuery', false);
mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

The deprecation warning doesn't have anything to do with the error you're receiving. Try removing the whole mongoose.set('strictQuery', true); line, and you'll get the same result.

Try replacing localhost with 127.0.0.1:

mongoose.connect('mongodb://127.0.0.1/fruitsDB')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hafez
  • 1,320
  • 2
  • 13
  • 24
  • Thanks a lot, @Hafez brother. Now it works perfect fine. Finally I can get to access my MongoDB. **Version:** MongoDB : 6.0.3 Mongoose : 6.8.0 – Rahul Saran Dec 10 '22 at 09:36
  • Did not worked for me still getting the same warning – Joseph Owigo Dec 10 '22 at 10:41
  • Thanks, it works for mongoose 6.9.1. – Chandresh Feb 09 '23 at 15:47
  • Welcome to Stack Overflow! [Stack Overflow is not a forum](https://meta.stackoverflow.com/questions/36818/would-you-recommend-stackexchange-sites-vs-other-types-of-forum/36828#36828). Please don't use Stack Overflow as such. Stack Overflow is not a forum. For example, questions asking for more information belong in comments to the question. Thanks in advance. – Peter Mortensen Feb 16 '23 at 23:00
2

mongoose.connect(process.env.MONGO_URL);

mongoose.set('strictQuery', true);

The above will gives you a warning even if you include that strictQuery line. The solution is nothing but place that strictQuery line before mongoose.connect:

mongoose.set('strictQuery', true);

mongoose.connect(process.env.MONGO_URL);

Then it works!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

Use:

mongoose.set('strictQuery', false);

mongoose.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true })
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

I am learning the same course on Udemy. Hafez's solution worked for me.

Simply replace

mongoose.connect('mongodb://localhost:27017/fruitsDB', {useNewUrlParser: true});

with

mongoose.set('strictQuery', true);
mongoose.connect('mongodb://127.0.0.1/fruitsDB');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0
mongoose.connect('mongodb://0.0.0.0/fruitsDB')

I think we're doing the same course. I just ignore the Mongoose deprecation warning.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

You can always try to change "localhost" from

mongoose.connect('mongodb://localhost:27017/fruitsDB');

to

mongoose.connect("mongodb://127.0.0.1:27017/fruitsDB");
Mor
  • 1
0

Yes, you just need to put this line of code above all.

mongoose.set( "strictQuery", false );
mongoose.connect( "mongodb://0.0.0.0:27017/NewDB", () => {
    console.log(`Connected to MongoDB`)
});

See Console Message

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

Place the strictQuery line before the connect line to avoid this issue:

const mongoose = require("mongoose");

mongoose.set('strictQuery', false);

mongoose.connect(
  "mongodb://localhost:27017/fruitsDB",
  {
    useNewUrlParser: true
  }
);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

I had the same issue. Just make sure you import (require) and use dotenv before the MongoDB connection statement. It worked for me.

const dotenv = require('dotenv');
dotenv.config({path: 'config.env'})

// MongoDB connection
connectDB();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 01 '23 at 06:43
0

I was facing the same problem.

Here we go, you can find solution in this picture.

  1. simply you need to add this code in "import section"

  2. mongoose.set('strictQuery',true);

  3. const app=express();

  4. const mongoose = require('mongoose');

  5. const express= require('express');

  6. mongoose.set('strictQuery', true);

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • Please review *[Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/)* (e.g., *"Images should only be used to illustrate problems that* ***can't be made clear in any other way,*** *such as to provide screenshots of a user interface."*) and [do the right thing](https://stackoverflow.com/posts/75395611/edit) (it covers answers as well). Thanks in advance. – Peter Mortensen Mar 30 '23 at 17:28
-1
// Mongoose setup //
const PORT = 8000;

mongoose
  .connect(
    process.env.MONGO_URL,
    {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    },
    **mongoose.set('strictQuery', false)**
  )
  .then(() => {
    app.listen(PORT, () => console.log(`Server port: ${PORT}`));
  })
  .catch((err) => console.log(`${err} did not connect`));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • An explanation would be in order. E.g., what is the idea/gist? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/74937014/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). Alternatively, where was it copied from? Was it generated by ChatGPT? – Peter Mortensen Feb 16 '23 at 23:35
-1
const mongoose = require("mongoose");

mongoose.set('strictQuery', false);
mongoose.connect("mongodb://127.0.0.1:27017/fruitsDB");

const fruitSchema = new mongoose.Schema({
    name: String,
    rating: Number,
    review: String
});

const Fruit = mongoose.model("Fruit", fruitSchema);

const fruit = new Fruit({
    name: "Apple",
    rating: 7,
    review: "Pretty solid!"
})

fruit.save();
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
-1
const mongoose = require("mongoose");
const DB = process.env.MONGO_URL;


const connectedDB = async () => {
  try {
    mongoose.set("strictQuery", true);
    const conn = await mongoose.connect(DB);
    console.log(`mongoDB connection : ${conn.connection.host}`.cyan.underline);
  } catch (err) {
    console.log(`No connection : ${err}`.red.underline);
  }
};

module.exports = connectedDB;
-1

Proper Way

const mongoose = require("mongoose");
mongoose.set("strictQuery", true);
mongoose
  .connect("mongodb://0.0.0.0:0/test", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log("Connected!");
  })
  .catch((err) => {
    console.log("oh no error");
    console.log(err);
  });
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
s.imran
  • 1
  • 2
-1
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';

const app = express();

app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());

const CONNECTION_URL = 
"mongodb+srv://<username>:<password>@cluster0.y3v2mwo.mongodb.net/? 
retryWrites=true&w=majority";
const PORT = process.env.PORT || 5000;

mongoose.set("strictQuery", false);

mongoose.connect(CONNECTION_URL)
.then(() => app.listen(PORT, () => console.log(`Server running on port: ${PORT}`)))
.catch(error => console.log(error.message));
Ali Raza
  • 670
  • 5
  • 15
-1

Simply do the below when your connection is established.

mongoose.set('strictQuery',false);
Dexter
  • 831
  • 8
  • 17
deep Kaur
  • 1
  • 2
-1
mongoose.set( "strictQuery", false );
mongoose.connect( "mongodb://0.0.0.0:27017/NewDB", () => {
    console.log(`Connected to MongoDB`)
});

This solves the Deprecation warning for me after several tries, thanks to the poster...

Tyler2P
  • 2,324
  • 26
  • 22
  • 31