skip to Main Content

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 DevelopmentFruitsProjectnode_modulesmongooselibdriversnode-mongodb-
nativecollection.js:158
          const err = new MongooseError(message);
                      ^

MongooseError: Operation `fruits.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (D:Web DevelopmentFruitsProjectnode_modulesmongoo
selibdriversnode-mongodb-nativecollection.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?

23

Answers


  1. 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')
    
    Login or Signup to reply.
  2. Remove this warning with just one line

    mongoose.set('strictQuery', true);
    mongoose.connect(process.env.MONGO_URL)
    
    Login or Signup to reply.
  3. 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);
        }
    
    Login or Signup to reply.
  4. 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');
    
    Login or Signup to reply.
  5. 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!

    Login or Signup to reply.
  6. mongoose.connect('mongodb://0.0.0.0/fruitsDB')
    

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

    Login or Signup to reply.
  7. 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});
    
    Login or Signup to reply.
  8. 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();
    
    Login or Signup to reply.
  9. 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);
    
    Login or Signup to reply.
  10. // 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`));
    
    Login or Signup to reply.
  11. Use:

    mongoose.set('strictQuery', false);
    
    mongoose.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true })
    
    Login or Signup to reply.
  12. You can always try to change "localhost" from

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

    to

    mongoose.connect("mongodb://127.0.0.1:27017/fruitsDB");
    
    Login or Signup to reply.
  13. 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();
    
    Login or Signup to reply.
  14. 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

    Login or Signup to reply.
  15. 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;
    
    Login or Signup to reply.
  16. 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
      }
    );
    
    Login or Signup to reply.
  17. 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);
      });
    
    Login or Signup to reply.
  18. 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();
    
    Login or Signup to reply.
  19. 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));
    
    Login or Signup to reply.
  20. 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
    });
    
    Login or Signup to reply.
  21. Simply do the below when your connection is established.

    mongoose.set('strictQuery',false);
    
    Login or Signup to reply.
  22. 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);

    Login or Signup to reply.
  23. 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…

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search