MongoDB object modeling designed to work in an asynchronous environment.

Related tags

Database mongoose
Overview

Mongoose

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks.

Slack Status Build Status NPM version

npm

Documentation

The official documentation website is mongoosejs.com.

Mongoose 5.0.0 was released on January 17, 2018. You can find more details on backwards breaking changes in 5.0.0 on our docs site.

Support

Plugins

Check out the plugins search site to see hundreds of related modules from the community. Next, learn how to write your own plugin from the docs or this blog post.

Contributors

Pull requests are always welcome! Please base pull requests against the master branch and follow the contributing guide.

If your pull requests makes documentation changes, please do not modify any .html files. The .html files are compiled code, so please make your changes in docs/*.pug, lib/*.js, or test/docs/*.js.

View all 400+ contributors.

Installation

First install Node.js and MongoDB. Then:

$ npm install mongoose

Importing

// Using Node.js `require()`
const mongoose = require('mongoose');

// Using ES6 imports
import mongoose from 'mongoose';

Mongoose for Enterprise

Available as part of the Tidelift Subscription

The maintainers of mongoose and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Overview

Connecting to MongoDB

First, we need to define a connection. If your app uses only one database, you should use mongoose.connect. If you need to create additional connections, use mongoose.createConnection.

Both connect and createConnection take a mongodb:// URI, or the parameters host, database, port, options.

await mongoose.connect('mongodb://localhost/my_database', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
  useCreateIndex: true
});

Once connected, the open event is fired on the Connection instance. If you're using mongoose.connect, the Connection is mongoose.connection. Otherwise, mongoose.createConnection return value is a Connection.

Note: If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed.

Important! Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc.

Defining a Model

Models are defined through the Schema interface.

const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

const BlogPost = new Schema({
  author: ObjectId,
  title: String,
  body: String,
  date: Date
});

Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:

The following example shows some of these features:

const Comment = new Schema({
  name: { type: String, default: 'hahaha' },
  age: { type: Number, min: 18, index: true },
  bio: { type: String, match: /[a-z]/ },
  date: { type: Date, default: Date.now },
  buff: Buffer
});

// a setter
Comment.path('name').set(function (v) {
  return capitalize(v);
});

// middleware
Comment.pre('save', function (next) {
  notify(this.get('email'));
  next();
});

Take a look at the example in examples/schema/schema.js for an end-to-end example of a typical setup.

Accessing a Model

Once we define a model through mongoose.model('ModelName', mySchema), we can access it through the same function

const MyModel = mongoose.model('ModelName');

Or just do it all at once

const MyModel = mongoose.model('ModelName', mySchema);

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name. For example, if you use

const MyModel = mongoose.model('Ticket', mySchema);

Then Mongoose will create the model for your tickets collection, not your ticket collection.

Once we have our model, we can then instantiate it, and save it:

const instance = new MyModel();
instance.my.key = 'hello';
instance.save(function (err) {
  //
});

Or we can find documents from the same collection

MyModel.find({}, function (err, docs) {
  // docs.forEach
});

You can also findOne, findById, update, etc.

const instance = await MyModel.findOne({ ... });
console.log(instance.my.key);  // 'hello'

For more details check out the docs.

Important! If you opened a separate connection using mongoose.createConnection() but attempt to access the model through mongoose.model('ModelName') it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:

const conn = mongoose.createConnection('your connection string');
const MyModel = conn.model('ModelName', schema);
const m = new MyModel;
m.save(); // works

vs

const conn = mongoose.createConnection('your connection string');
const MyModel = mongoose.model('ModelName', schema);
const m = new MyModel;
m.save(); // does not work b/c the default connection object was never connected

Embedded Documents

In the first example snippet, we defined a key in the Schema that looks like:

comments: [Comment]

Where Comment is a Schema we created. This means that creating embedded documents is as simple as:

// retrieve my model
const BlogPost = mongoose.model('BlogPost');

// create a blog post
const post = new BlogPost();

// create a comment
post.comments.push({ title: 'My comment' });

post.save(function (err) {
  if (!err) console.log('Success!');
});

The same goes for removing them:

BlogPost.findById(myId, function (err, post) {
  if (!err) {
    post.comments[0].remove();
    post.save(function (err) {
      // do something
    });
  }
});

Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it's bubbled to the save() error callback, so error handling is a snap!

Middleware

See the docs page.

Intercepting and mutating method arguments

You can intercept method arguments via middleware.

For example, this would allow you to broadcast changes about your Documents every time someone sets a path in your Document to a new value:

schema.pre('set', function (next, path, val, typel) {
  // `this` is the current Document
  this.emit('set', path, val);

  // Pass control to the next pre
  next();
});

Moreover, you can mutate the incoming method arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to next:

.pre(method, function firstPre (next, methodArg1, methodArg2) {
  // Mutate methodArg1
  next("altered-" + methodArg1.toString(), methodArg2);
});

// pre declaration is chainable
.pre(method, function secondPre (next, methodArg1, methodArg2) {
  console.log(methodArg1);
  // => 'altered-originalValOfMethodArg1'

  console.log(methodArg2);
  // => 'originalValOfMethodArg2'

  // Passing no arguments to `next` automatically passes along the current argument values
  // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
  // and also equivalent to, with the example method arg
  // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
  next();
});

Schema gotcha

type, when used in a schema has special meaning within Mongoose. If your schema requires using type as a nested property you must use object notation:

new Schema({
  broken: { type: Boolean },
  asset: {
    name: String,
    type: String // uh oh, it broke. asset will be interpreted as String
  }
});

new Schema({
  works: { type: Boolean },
  asset: {
    name: String,
    type: { type: String } // works. asset is an object with a type property
  }
});

Driver Access

Mongoose is built on top of the official MongoDB Node.js driver. Each mongoose model keeps a reference to a native MongoDB driver collection. The collection object can be accessed using YourModel.collection. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one notable exception that YourModel.collection still buffers commands. As such, YourModel.collection.find() will not return a cursor.

API Docs

Find the API docs here, generated using dox and acquit.

Related Projects

MongoDB Runners

Unofficial CLIs

Data Seeding

Express Session Stores

License

Copyright (c) 2010 LearnBoost <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Mongoose slows down performance of VSCode (TSServer) by a lot

    Mongoose slows down performance of VSCode (TSServer) by a lot

    Do you want to request a feature or report a bug?

    bug

    What is the current behavior?

    It slows down vscode by a lot, even with small projects. I have a very small project, with like 2 small schemas, and the 2 other files, containing on average 160 lines of code, and vscode slows down a lot as soon as I install mongoose. This does not happen when I install most other libraries (haven't tested them all lmao). If I uninstall mongoose, it comes back and works perfectly normal. To clarify "slowing down" means that typescript language server needs 3-5 seconds to realise that I'm importing somethign invalid, and just vscode in general to realise I'm importing something that's never used takes around 2-4 seconds. Usually it happens in under a second so like.. you know... And it's not like vscode is taking a lot of ram/cpu either, it just grows slow. Btw I think this is a mongoose issue, since it happens with no other library, its a special case here Reloading typescript server or project doesn't help

    If the current behavior is a bug, please provide the steps to reproduce.

    Have vscode to edit your code Install mongoose on your current project (npm i mongoose

    My tsconfig.json:

    {
        "compilerOptions": {
            "allowJs": true,
            "moduleResolution": "Node",
            "esModuleInterop": true,
            "target": "ES6",
            "resolveJsonModule": true,
            "outDir": "./dist",
            "checkJs": true,
            "module": "CommonJS",
            "lib": ["ESNext"]
        },
        "include": ["src"]
    }
    

    What is the expected behavior?

    It to not be like this, lmao.

    What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

    Node: v16.2.0 Mongoose: 5.12.13 Linux: 5.12.7-arch1-1

    typescript 
    opened by ShadiestGoat 217
  • DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead

    DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead

    DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use openUri() instead, or set the useMongoClient option if using connect() or createConnection()

    Mongoose 4.11.0, MongoDB 2.2.29, NodeJS 8.1.2

    opened by cosminn777 158
  • js-bson: Failed to load c++ bson extension, using pure JS version

    js-bson: Failed to load c++ bson extension, using pure JS version

    I clicked on Fork, cloned the repo and I attached this module to my project. I get this error

    js-bson: Failed to load c++ bson extension, using pure JS version
    

    nodejs v0.11.13, latest osx. It looks that the problem is with the mongodb module (works with bson 0.2.15).

    opened by xpepermint 117
  • pre, post middleware are not executed on findByIdAndUpdate

    pre, post middleware are not executed on findByIdAndUpdate

    Because a findAndUpdate method is presented to cut down the following code:

     Model.findById(_id, function (err, doc) {
          if (doc) {
              doc.field = 'value';
              doc.save(function (err) {
                     // do something;
              });
          }
     });
    

    to this:

    Model
       .findByIdAndUpdate(_id, {$set: {field: 'value'}}, function (err, doc) {
            // do something 
        });
    

    We need to use pre, post middleware exactly the same. At now pre, post middleware are not executed when I make findByIdAndUpdate.

    opened by skotchio 102
  • Suggestion for single embedded document support

    Suggestion for single embedded document support

    Hi,

    One of my challenges with mongoose is to have a single embedded doc in a doc, this patch allows this kind of schema declaration:

    var mongoose = require('mongoose'), Schema = mongoose.Schema;

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

    var PersonSchema = new Schema({ FirstName: {type: String, required: true}, LastName: String });

    var BlogPostSchema = new Schema({ creator: PersonSchema });

    /**

    • Define model. */

    var BlogPost = mongoose.model('BlogPost', BlogPostSchema); var Person = mongoose.model('Person', PersonSchema);

    var person = new Person({FirstName: 'Paulo', LastName: 'Lopes'});

    var post = new BlogPost({title: 'test', creator: person});

    post.save(function(err) { if (err) return console.log(err); BlogPost.find({}, function(err, docs) { if(err) return console.log(err); console.log(docs[0].creator); docs[0].creator = null; docs[0].save(function(err) { if(err) return console.log(err); mongoose.disconnect(); }); }); });

    I don't know much about the internals of mongoose but this seems to work for me... could someone review and give some feedback? Thanks

    enhancement 
    opened by pmlopes 101
  • Calling populate on embedded doc of embedded doc

    Calling populate on embedded doc of embedded doc

    Hey, I have the following schemas ( simplified for issue)

    User = new Schema login:String

    A = new Schema emb: [B] comments: [Comments]

    //and following embedded schemas

    B = new Schema comments: [Comments]

    Comments = new Schema creator: type: ObjectId ref: 'User' message: String

    Now while populate works on A eg A.find().populate('comments.creator')

    it doesn't work on the double nested embedded doc eg A.find().populate('emb.comments.creator')

    Any ideas?

    new feature 
    opened by dmmalam 93
  • added support for discriminator mapping (closes #1003)

    added support for discriminator mapping (closes #1003)

    So I gave discriminator mapping a shot. After coding this out, it feels pretty natural and seems to fit well with the current API of mongoose.

    Anyway, a quick example of how it works:

    function BaseSchema() {
        Schema.apply(this, arguments);
    
        this.add({
            name: String,
            createdAt: { type: Date, default: Date.now }
        });
    }
    util.inherits(BaseSchema, Schema);
    
    var EventSchema = new BaseSchema();
    
    var ImpressionEvent = new BaseSchema();
    
    var ConversionEvent = new BaseSchema({
        revenue: Number
    });
    
    var Base = mongoose.model('Event', EventSchema),
    var Impression = Base.discriminator('Impression', ImpressionEvent),
    var Conversion = Base.discriminator('Conversion', ConversionEvent);
    

    Then assuming we have inserted a single document for each event in the order of Base, Impression, and Conversion:

    Base.find({}, function(err, events) {
        expect.ok(events[0] instanceof Base);       // true
        expect.ok(events[1] instanceof Impression); // true
        expect.ok(events[2] instanceof Conversion); // true
        expect.ok(events[2] instanceof Base);       // false
    
        // however
        expect.ok(events[2].schema instanceof BaseSchema); // true
    });
    

    Lastly, if you take a the specific discriminator type model, it will query for only the documents of that type:

    // find all conversion events
    Conversion.find({}, function(err, events) {
        expect.equal(events.length, 1);
    });
    
    // or a single document
    Conversion.findOne({}, function(err, event) {
        expect.ok(event instanceof Conversion); // true
    });
    
    // or querying for a specific id which is an invalid type (produces query { _id: ..., __t: 'Conversion' })
    Conversion.findOne({ _id: impression.id }}, function(err, event) {
        expect.equal(event, null); // true
    });
    

    Just one thing before moving too far forward: I introduced a new method "discriminator" to be clear of what you're doing. It creates a model in the same connection and returns it and does some other stuff behind the scenes. We could also make the static method Model.model do the same (or alias / remove discriminator method) if the community would rather have the following instead:

    var Base = mongoose.model('Event', EventSchema);
    var Impression = Base.model('Impression', ImpressionEvent),
    var Conversion = Base.model('Conversion', ConversionEvent);
    

    Another note, in my example, I'm using util.inherit to simply show that you can have a base model. This is completely optional. You can technically store whatever schema's you want and they don't have to inherit from one another. I'm also +1 for creating an extend method in Schema to shortcut schema inheritance.

    Anyway, here you go! :) :surfer:

    Todos

    • [ ] Reference mapping validation (throw error when reference type doesn't match)
    • [ ] More regression tests (reference mapping, ...)
    • [x] Force discriminator schemas to inherit root (?)
    • [x] Model inheritance (?)
    • [ ] ...
    Off topic:

    After this, we can discuss adding "discriminator" style mapping to embedded documents. They are sort of unrelated in the scope of this PR... Unless someone can think of a way to combine the two in a mongoose style fashion :P

    opened by j 85
  • Mongoose 4.6.2 produces error

    Mongoose 4.6.2 produces error "MongoError: no primary found in replicaset" while 4.4.19 works just fine

    Simple connection to a MongoDB replica set. Works great in Mongoose 4.4.19 but not in 4.6.2

    mongoURI = "mongodb://IP:27017,IP:27017/" + dbName + "?replicaSet=my_replica_set";

    Using 4.6.2, I have tried the following:

    • defining replset in connection options
    • connectWithNoPrimary: true
    • tried both mongoose.createConnection vs mongoose.connect
    • included and excluded arbiter node in the connection string

    If connection string only uses one database, it works fine. I am really curious as to why this error occurs. Any thoughts?

    Full Error:

    /Users/adeel/dev/navi/euler/node_modules/mongodb/lib/replset.js:360 process.nextTick(function() { throw err; }) ^ MongoError: no primary found in replicaset at /Users/adeel/dev/navi/euler/node_modules/mongodb-core/lib/topologies/replset.js:631:32 at . (/Users/adeel/dev/navi/euler/node_modules/mongodb-core/lib/topologies/replset.js:421:24) at g (events.js:286:16) at emitOne (events.js:96:13) at emit (events.js:188:7) at . (/Users/adeel/dev/navi/euler/node_modules/mongodb-core/lib/topologies/server.js:313:21) at emitOne (events.js:96:13) at emit (events.js:188:7) at . (/Users/adeel/dev/navi/euler/node_modules/mongodb-core/lib/connection/pool.js:260:12) at g (events.js:286:16) at emitTwo (events.js:106:13) at emit (events.js:191:7) at Socket. (/Users/adeel/dev/navi/euler/node_modules/mongodb-core/lib/connection/connection.js:162:49) at Socket.g (events.js:286:16) at emitOne (events.js:96:13) at Socket.emit (events.js:188:7)

    needs clarification 
    opened by adeelzaman 82
  • Is it possible to populate without `_id` ?

    Is it possible to populate without `_id` ?

    I checked the API http://mongoosejs.com/docs/populate.html and tried out. It seems that populate can only works on foreign _id. Even there is a match option, it just add more filtering condition on _id query condition. There is no way to just populate with fields not involved with _id.

    In my project, we keep the _id as ObjectId and has another field as auto-increment Number. For example, customers model has _id as Object and cuid as incremental number. Other collections just reference to cuid not to _id.

    Is would be great to be able to customize this? Is there any design limitation causing this feature missing?

    enhancement 
    opened by mocheng 82
  • Deprecation Warning

    Deprecation Warning

    I'm getting this warning

    (node:3341) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
    

    after I do

    driver.createCar({
              carName: 'jeep',
              availableSeats: 4,
            }, callback);
    

    driver is an instance of Driver class

    const carSchema = new Schema({
      carName: String,
      availableSeats: Number,
      createdOn: { type: Date, default: Date.now },
    });
    const driverSchema = new Schema({
      email: String,
      name: String,
      city: String,
      phoneNumber: String,
      cars: [carSchema],
      userId: {
        type: Schema.Types.ObjectId,
        required: true,
      },
      createdOn: { type: Date, default: Date.now },
    });
    const DriverModel = mongoose.model('Driver', driverSchema);
    
    class Driver extends DriverModel {
      getCurrentDate() {
        return moment().format();
      }
      create(cb) {
        // save driver
        this.createdOn = this.getCurrentDate();
        this.save(cb);
      }
      remove(cb) {
        super.remove({
          _id: this._id,
        }, cb);
      }
      createCar(carData, cb) {
        this.cars.push(carData);
        this.save(cb);
      }
      getCars() {
        return this.cars;
      }
    }
    

    any thoughts about what Im doing wrong?

    help 
    opened by saudelog 79
  • { useUnifiedTopology: true } leads to MongoDB connection error: MongoTimeoutError: Server selection timed out after 30000 ms

    { useUnifiedTopology: true } leads to MongoDB connection error: MongoTimeoutError: Server selection timed out after 30000 ms

    Do you want to request a feature or report a bug?

    A bug.

    What is the current behavior?

    After updating to Mongoose 5.7.1, the following warning appeared:

    (node:41563) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
        at parseFn (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/mongoose/node_modules/mongodb/lib/operations/connect.js:312:5)
        at parseConnectionString (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/mongoose/node_modules/mongodb/lib/core/uri_parser.js:628:3)
        at connect (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/mongoose/node_modules/mongodb/lib/operations/connect.js:266:3)
        at ConnectOperation.execute (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/mongoose/node_modules/mongodb/lib/operations/connect.js:191:5)
        at executeOperation (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/mongoose/node_modules/mongodb/lib/operations/execute_operation.js:83:26)
        at MongoClient.connect (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js:216:10)
        at Promise (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/mongoose/lib/connection.js:632:12)
        at Promise._execute (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/bluebird/js/release/debuggability.js:313:9)
        at Promise._resolveFromExecutor (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/bluebird/js/release/promise.js:488:18)
        at new Promise (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/bluebird/js/release/promise.js:79:10)
        at NativeConnection.Connection.openUri (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/mongoose/lib/connection.js:629:19)
        at Mongoose.connect (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/mongoose/lib/index.js:327:15)
        at Object.connect (/Users/tschaffter/dev/PHCCollaborationPortal/server/app.js:17:44)
        at Module._compile (internal/modules/cjs/loader.js:778:30)
        at Module._compile (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/pirates/lib/index.js:99:24)
        at Module._extensions..js (internal/modules/cjs/loader.js:789:10)
        at Object.newLoader [as .js] (/Users/tschaffter/dev/PHCCollaborationPortal/node_modules/pirates/lib/index.js:104:7)
        at Module.load (internal/modules/cjs/loader.js:653:32)
        at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
        at Function.Module._load (internal/modules/cjs/loader.js:585:3)
        at Module.require (internal/modules/cjs/loader.js:692:17)
        at require (internal/modules/cjs/helpers.js:25:18)
        at Object.<anonymous> (/Users/tschaffter/dev/PHCCollaborationPortal/server/index.js:12:28)
        at Module._compile (internal/modules/cjs/loader.js:778:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
        at Module.load (internal/modules/cjs/loader.js:653:32)
        at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
        at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    

    I added useUnifiedTopology: true to my mongoose config object as suggested by the message, even though I'm not using MongoDB replica set or sharded cluster. Here is how I configure and connect using mongoose:

            options: {
                // https://mongoosejs.com/docs/deprecations.html
                useNewUrlParser: true,
                useFindAndModify: false,
                useCreateIndex: true,
                useUnifiedTopology: true,
                reconnectTries: 30,
                reconnectInterval: 500, // in ms
            }
        },
    

    and here is where I used this mongo.options object:

    // Connect to MongoDB
    const mongooseConnectionPromise = mongoose.connect(config.mongo.uri, config.mongo.options);
    mongoose.connection.on('error', err => {
        console.error(`MongoDB connection error: ${err}`);
        process.exit(-1); // eslint-disable-line no-process-exit
    });
    

    The warning is gone but the issue is that mongoose is now no longer able to connect:

    MongoDB connection error: MongoTimeoutError: Server selection timed out after 30000 ms
    [nodemon] app crashed - waiting for file changes before starting...
    

    Here is how I run MongoDB using docker during development:

    docker run -p ${MONGO_PORT}:${MONGO_PORT} --name mongo -d mongo
    

    If the current behavior is a bug, please provide the steps to reproduce.

    See above

    What is the expected behavior?

    Mongoose should remove the deprecation warning and run fine when using useUnifiedTopology: true as mongoose suggests.

    What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

    Node: v10.16.2 Mongoose: 5.7.1 (latest) MongoDB: db version v4.2.0

    Related issues:

    • https://github.com/Automattic/mongoose/issues/8156
    • https://github.com/Automattic/mongoose/issues/8169
    can't reproduce 
    opened by tschaffter 78
  • Mongoose client not reconnecting to primary Mongo replica after replica election

    Mongoose client not reconnecting to primary Mongo replica after replica election

    Prerequisites

    • [X] I have written a descriptive issue title

    Mongoose version

    6.6.0

    Node.js version

    14.20.1

    MongoDB version

    4.4.5

    Operating system

    Linux

    Operating system version (i.e. 20.04, 11.3, 10)

    Debian Bullseye Slim

    Issue

    Mongo: 4.4.5 Mongoose: 6.6.0 Node: 14.20.1 (bullseye-slim) Docker: 20.10.8

    Problem

    We have a docker swarm with multiple servers and a mongo stack with 3 replicas each on different servers. Our rs1(primary) replica goes down due to a Docker restart. When this happens an election occurs and rs3 is selected as the new primary. After rs1 is re-elected a few seconds later, some of our backend client replicas receive the following error when making queries:

    MongooseServerSelectionError: Server selection timed out after 30000 ms
        at Function.Model.$wrapCallback (/usr/share/backend-server/node_modules/mongoose/lib/model.js:5192:32)
        at /usr/share/backend-server/node_modules/mongoose/lib/query.js:4901:21
        at /usr/share/backend-server/node_modules/mongoose/lib/helpers/promiseOrCallback.js:41:5
        at new Promise (<anonymous>)
        at promiseOrCallback (/usr/share/backend-server/node_modules/mongoose/lib/helpers/promiseOrCallback.js:40:10)
        at model.Query.exec (/usr/share/backend-server/node_modules/mongoose/lib/query.js:4900:10)
        at model.Query.Query.then (/usr/share/backend-server/node_modules/mongoose/lib/query.js:4983:15) {
      reason: TopologyDescription {
        type: 'ReplicaSetNoPrimary',
        servers: Map(3) {
          'rs1:27017' => [ServerDescription],
          'rs2:27017' => [ServerDescription],
          'rs3:27017' => [ServerDescription]
        },
        stale: false,
        compatible: true,
        heartbeatFrequencyMS: 10000,
        localThresholdMS: 15,
        setName: 'rs0',
        maxElectionId: new ObjectId("7fffffff0000000000000053"),
        maxSetVersion: 1,
        commonWireVersion: 0,
        logicalSessionTimeoutMinutes: 30
      },
      code: undefined
    }
    

    Upon checking the status of the replicas, rs1 is the primary and most of our backend clients fulfill queries correctly. We have seen this issue occur on two separate occasions and we are unsure why some Mongoose clients are unable to find the primary replica after the election. We have been unable to recreate the error intentionally.

    Our Setup

    docker-compose.yml:

    The image being used is for Mongodb 4.4.5

    version: '3.3'
    secrets:
      mongo_cluster_key:
        external: true
    services:
      rs1:
        image: mongodb-custom:v1.0.0
        command: mongod --keyFile /run/secrets/mongo_cluster_key --replSet "rs0"
        networks:
          - mongo
        ports:
          - 27017:27017
        secrets:
          - source: mongo_cluster_key
            target: mongo_cluster_key
            uid: '999'
            gid: '999'
            mode: 0400
        environment:
        - MONGO_INITDB_ROOT_USERNAME=admin 
        - MONGO_INITDB_ROOT_PASSWORD=password
        - MONGO_INITDB_DATABASE=admin
        - MAIN_MONGO_DB_NAME=testing
        - MAIN_MONGO_DB_USERNAME=test
        - MAIN_MONGO_DB_PASSWORD=password
        - MAIN_MONGO_DB_ROLE=readWrite
        deploy:
          replicas: 1
        volumes:
          - rs1:/data/db 
          - rs1:/data/configdb
      rs2:
        image: mongodb-custom:v1.0.0
        command: mongod --keyFile /run/secrets/mongo_cluster_key --replSet "rs0"
        networks:
          - mongo
        secrets:
          - source: mongo_cluster_key
            target: mongo_cluster_key
            uid: '999'
            gid: '999'
            mode: 0400
        environment:
        - MONGO_INITDB_ROOT_USERNAME=admin 
        - MONGO_INITDB_ROOT_PASSWORD=password
        - MONGO_INITDB_DATABASE=admin
        - MAIN_MONGO_DB_NAME=testing
        - MAIN_MONGO_DB_USERNAME=test
        - MAIN_MONGO_DB_PASSWORD=password
        - MAIN_MONGO_DB_ROLE=readWrite
        deploy:
          replicas: 1
        volumes:
          - rs2:/data/db 
          - rs2:/data/configdb
      rs3:
        image: mongodb-custom:v1.0.0
        command: mongod --keyFile /run/secrets/mongo_cluster_key --replSet "rs0"
        networks:
          - mongo
        secrets:
          - source: mongo_cluster_key
            target: mongo_cluster_key
            uid: '999'
            gid: '999'
            mode: 0400
        environment:
        - MONGO_INITDB_ROOT_USERNAME=admin 
        - MONGO_INITDB_ROOT_PASSWORD=password
        - MONGO_INITDB_DATABASE=admin
        - MAIN_MONGO_DB_NAME=testing
        - MAIN_MONGO_DB_USERNAME=test
        - MAIN_MONGO_DB_PASSWORD=password
        - MAIN_MONGO_DB_ROLE=readWrite
        deploy:
          replicas: 1
        volumes:
          - rs3:/data/db 
          - rs3:/data/configdb
      rs:
        image: mongodb-custom:v1.0.0
        command: /usr/local/bin/replica-init.sh
        networks:
          - mongo
        secrets:
          - source: mongo_cluster_key
            target: mongo_cluster_key
            uid: '999'
            gid: '999'
            mode: 0400
        environment:
        - MONGO_INITDB_ROOT_USERNAME=admin 
        - MONGO_INITDB_ROOT_PASSWORD=password
        - MONGO_INITDB_DATABASE=admin
        - MAIN_MONGO_DB_NAME=testing
        - MAIN_MONGO_DB_USERNAME=test
        - MAIN_MONGO_DB_PASSWORD=password
        - MAIN_MONGO_DB_ROLE=readWrite
        deploy:
          restart_policy:
            condition: on-failure
            delay: 5s
            max_attempts: 10
    volumes:
      rs1:
        driver: local
      rs2:
        driver: local
      rs3:
        driver: local
    networks:
      mongo:
        driver: overlay
        driver_opts:
          encrypted: "true"
        internal: true
        attachable: true
    

    replica-init.sh:

    #!/bin/bash
    # Make sure 3 replicas available
    for rs in rs1 rs2 rs3;do
      mongo --host $rs --eval 'db'
      if [ $? -ne 0 ]; then
        exit 1
      fi
    done
    MONGO_INITDB_ROOT_USERNAME="$(< $MONGO_INITDB_ROOT_USERNAME_FILE)"
    MONGO_INITDB_ROOT_PASSWORD="$(< $MONGO_INITDB_ROOT_PASSWORD_FILE)"
    # Connect to rs1 and configure replica set if not done
    status=$(mongo --host rs1 --quiet --eval 'rs.status().members.length')
    if [ $? -ne 0 ]; then
      # Replicaset not yet configured
      mongo --username $MONGO_INITDB_ROOT_USERNAME -p $MONGO_INITDB_ROOT_PASSWORD --host rs1 --eval 'rs.initiate({ _id: "rs0", version: 1, members: [ { _id: 0, host : "rs1", priority: 100 }, { _id: 1, host : "rs2", priority: 2 }, { _id: 2, host : "rs3", priority: 2 } ] })';
    fi
    

    backend-server.js

    const mongoose = require('mongoose');
    // MongoDB Connection Class
    class MongoDB {
      constructor() {
        mongoose
          .connect('mongodb://test:password@rs1:27017,rs2:27017,rs3:27017/testing?replicaSet=rs0')
          .then(() => {
            console.log('Connected to MongoDB');
          })
          .catch((err) => {
            console.error('MongoDB Error: ', err.message);
          });
        // Add error handler while connected
        mongoose.connection.on('error', (err) => {
          console.log('MongoDB Error: ', err);
        });
        mongoose.pluralize(null);
      }
    }
    module.exports = new MongoDB();
    

    We have 2500 connections, between 60 clients, so using the directConnection flag may be too slow.

    What we've tried

    1. We have tested the replica election process and it seems to be electing a secondary node as the new primary correctly once the original primary goes down. It also is re-electing the original primary once that node comes back up.
    2. We have verified that the priorities for each primary and secondary node are set correctly.
    3. The Docker Swarm DNS resolves rs1's hostname and is reachable from the backend server container that has a Mongoose client receiving the error above.

    We verified that the authentication and connection strings are all setup correctly. When this error occurs, restarting the backend server docker containers fixes the issue. We are not receiving any connection errors in our backend server logs. Errors only appear when querying the database.

    help help wanted 
    opened by austinconry 4
  • Question: Does mongoose have/need warmup?

    Question: Does mongoose have/need warmup?

    Prerequisites

    • [X] I have written a descriptive issue title
    • [X] I have searched existing issues to ensure the issue has not already been raised

    Issue

    Hi!

    I'm using mongoose to connect to my MongoDB cluster which is hosted on Atlas. The first few queries (regardless of the collection) upon server startup are slower, almost like it needs to warm up. (e.g. the same query executed the first few times needs ~2 seconds to complete, but after that it consistently completes in ~700ms)

    This doesn't appear to be the case with mongosh CLI tool from MongoDB.

    I know the question is kind of vague, but I'm just wondering is there a warmup procedure/options used by mongoose that impact initial performance/responsivness?

    Thanks!

    help 
    opened by VladimirMikulic 1
  • Customize unique error message in schema

    Customize unique error message in schema

    Prerequisites

    • [X] I have written a descriptive issue title
    • [X] I have searched existing issues to ensure the feature has not already been requested

    🚀 Feature Proposal

    See https://github.com/Automattic/mongoose/issues/1225#issuecomment-1359689295 . Should be able to specify an error message for unique: true on a given path, and have Mongoose handle that.

    Motivation

    No response

    Example

    No response

    new feature enhancement 
    opened by vkarpov15 2
  • 7.0 driver cleanup

    7.0 driver cleanup

    Summary

    Make drivers easier to implement, and minimize how hard-coded the MongoDB driver is in our code. Also remove the require('../driver').get() calls that tend to confuse bundlers and cause hard-to-debug issues when implementing custom drivers. Drivers are now fully scoped to a single Mongoose instance, minus the driver.js file which we still need to remove.

    Examples

    opened by vkarpov15 1
  • mongoose updateOne add pre then no return

    mongoose updateOne add pre then no return

    Prerequisites

    • [X] I have written a descriptive issue title

    Mongoose version

    6.5.1

    Node.js version

    v14.17.3

    MongoDB version

    4.2

    Operating system

    macOS

    Operating system version (i.e. 20.04, 11.3, 10)

    12.4

    Issue

    1. schema.pre('updateOne',async function (doc, next) { const updateInfo = {} // do stuff... this._update.$set = { ...updateInfo } return next() })

    2. const result = await model.updateOne( { nickname:'mark', }, { $set: {updatedAt:new Date() } } ) console.log(result) // undefined

    why the result is undefined

    confirmed-bug 
    opened by tingfeima 2
Releases(6.8.2)
  • 6.8.2(Dec 28, 2022)

    6.8.2 / 2022-12-28

    • fix(schema): propagate strictQuery to implicitly created schemas for embedded discriminators #12827 #12796
    • fix(model): respect discriminators with Model.validate() #12824 #12621
    • fix(query): fix unexpected validation error when doing findOneAndReplace() with a nullish value #12826 #12821
    • fix(discriminator): apply built-in plugins to discriminator schema even if mergeHooks and mergePlugins are both false #12833 #12696
    • fix(types): add option "overwriteModels" as a schema option #12817 #12816 hasezoey
    • fix(types): add property "defaultOptions" #12818 hasezoey
    • docs: make search bar respect documentation version, so you can search 5.x docs #12548
    • docs(typescript): make note about recommending strict mode when using auto typed schemas #12825 #12420
    • docs: add section on sorting to query docs #12588 IslandRhythms
    • test(query.test): add write-concern option #12829 hasezoey
    Source code(tar.gz)
    Source code(zip)
  • 6.8.1(Dec 19, 2022)

    6.8.1 / 2022-12-19

    • fix(query): avoid throwing circular dependency error if same object is used in multiple properties #12774 orgads
    • fix(map): return value from super.delete() #12777 danbrud
    • fix(populate): handle virtual populate underneath document array with justOne=true and sort set where 1 element has only 1 result #12815 #12730
    • fix(update): handle embedded discriminators when casting array filters #12802 #12565
    • fix(populate): avoid calling transform if there's no populate results and using lean #12804 #12739
    • fix(model): prevent index creation on syncIndexes if not necessary #12785 #12250 lpizzinidev
    • fix(types): correctly infer this when using pre('updateOne') with { document: true, query: false } #12778
    • fix(types): make InferSchemaType: consider { required: boolean } required if it isn't explicitly false #12784 JavaScriptBach
    • docs: replace many occurrences of "localhost" with "127.0.0.1" #12811 #12741 hasezoey SadiqOnGithub
    • docs(mongoose): Added missing options to set #12810 lpizzinidev
    • docs: add info on $locals parameters to getters/setters tutorial #12814 #12550 IslandRhythms
    • docs: make Document.prototype.$clone() public #12803
    • docs(query): updated explanation for slice #12776 #12474 lpizzinidev
    • docs(middleware): fix broken links #12787 lpizzinidev
    • docs(queries): fixed broken links #12790 lpizzinidev
    Source code(tar.gz)
    Source code(zip)
  • 6.8.0(Dec 5, 2022)

    6.8.0 / 2022-12-05

    • feat: add alpha support for Deno #12397 #9056
    • feat: add deprecation warning for default strictQuery #12666
    • feat: upgrade to MongoDB driver 4.12.1
    • feat(schema): add doc as second params to validation message function #12564 #12651 IslandRhythms
    • feat(document): add $clone method #12549 #11849 lpizzinidev
    • feat(populate): allow overriding localField and foreignField for virtual populate #12657 #6963 IslandRhythms
    • feat(schema+types): add { errorHandler: true } option to Schema post() for better TypeScript support #12723 #12583
    • feat(debug): allow setting debug on a per-connection basis #12704 #12700 lpizzinidev
    • feat: add rewind function to QueryCursor #12710 passabilities
    • feat(types): infer timestamps option from schema #12731 #12069
    • docs: change links to not link to api.html anymore #12644 hasezoey
    Source code(tar.gz)
    Source code(zip)
  • 6.7.5(Nov 30, 2022)

    6.7.5 / 2022-11-30

    • fix(schema): copy indexes when calling add() with schema instance #12737 #12654
    • fix(query): handle deselecting _id when another field has schema-level select: false #12736 #12670
    • fix(types): support using UpdateQuery in bulkWrite() #12742 #12595
    • docs(middleware): added note about execution policy on subdocuments #12735 #12694 lpizzinidev
    • docs(validation): clarify context for update validators in validation docs #12738 #12655 IslandRhythms
    Source code(tar.gz)
    Source code(zip)
  • 6.7.4(Nov 28, 2022)

    6.7.4 / 2022-11-28

    • fix: allow setting global strictQuery after Schema creation #12717 #12703 lpizzinidev
    • fix(cursor): make eachAsync() avoid modifying batch when mixing parallel and batchSize #12716
    • fix(types): infer virtuals in query results #12727 #12702 #12684
    • fix(types): correctly infer ReadonlyArray types in schema definitions #12720
    • fix(types): avoid typeof Query with generics for TypeScript 4.6 support #12712 #12688
    • chore: avoid bundling .tgz files when publishing #12725 hasezoey
    Source code(tar.gz)
    Source code(zip)
  • 6.7.3(Nov 22, 2022)

    6.7.3 / 2022-11-22

    • fix(document): handle setting array to itself after saving and pushing a new value #12672 #12656
    • fix(types): update replaceWith pipeline stage #12715 coyotte508
    • fix(types): remove incorrect modelName type definition #12682 #12669 lpizzinidev
    • fix(schema): fix setupTimestamps for browser.umd #12683 raphael-papazikas
    • docs: correct justOne description #12686 #12599 tianguangcn
    • docs: make links more consistent #12690 #12645 hasezoey
    • docs(document): explain that $isNew is false in post('save') hooks #12685 #11990
    • docs: fixed line causing a "used before defined" linting error #12707 sgpinkus
    Source code(tar.gz)
    Source code(zip)
  • 6.7.2(Nov 7, 2022)

    6.7.2 / 2022-11-07

    • fix(discriminator): skip copying base schema plugins if applyPlugins == false #12613 #12604 lpizzinidev
    • fix(types): add UUID to types #12650 #12593
    • fix(types): allow setting SchemaTypeOptions' index property to IndexOptions #12562
    • fix(types): set this to doc type in SchemaType.prototype.validate() #12663 #12590
    • fix(types): correct handling for model #12659 #12573
    • fix(types): pre hook with deleteOne should resolve this as Query #12642 #12622 lpizzinidev
    Source code(tar.gz)
    Source code(zip)
  • 6.7.1(Nov 2, 2022)

    6.7.1 / 2022-11-02

    • fix(query): select Map field with select: false when explicitly requested #12616 #12603 lpizzinidev
    • fix: correctly find paths underneath single nested document with an array of mixed #12605 #12530
    • fix(populate): better support for populating maps of arrays of refs #12601 #12494
    • fix(types): add missing create constructor signature override type #12585 naorpeled
    • fix(types): make array paths optional in inferred type of array default returns undefined #12649 #12420
    • fix(types): improve ValidateOpts type #12606 Freezystem
    • docs: add Lodash guide highlighting issues with cloneDeep() #12609
    • docs: removed v5 link from v6 docs #12641 #12624 lpizzinidev
    • docs: removed outdated connection example #12618 lpizzinidev
    Source code(tar.gz)
    Source code(zip)
  • 6.7.0(Oct 24, 2022)

    6.7.0 / 2022-10-24

    • feat: upgrade to mongodb driver 4.11.0 #12446
    • feat: add UUID Schema Type (BSON Buffer SubType 4) #12268 #3208 hasezoey
    • feat(aggregation): add $fill pipeline stage #12545 raphael-papazikas
    • feat(types+schema): allow defining schema paths using mongoose.Types.* to work around TS type inference issues #12352
    • feat(schema): add alias() method that makes it easier to define multiple aliases for a given path #12368
    • feat(model): add mergeHooks option to Model.discriminator() to avoid duplicate hooks #12542
    • feat(document): add $timestamps() method to set timestamps for save(), bulkSave(), and insertMany() #12540
    Source code(tar.gz)
    Source code(zip)
  • 6.6.7(Oct 21, 2022)

    6.6.7 / 2022-10-21

    • fix: correct browser build and improve isAsyncFunction check for browser #12577 #12576 #12392
    • fix(query): allow overwriting discriminator key with overwriteDiscriminatorKey if strict: 'throw' #12578 #12513
    Source code(tar.gz)
    Source code(zip)
  • 6.6.6(Oct 21, 2022)

    6.6.6 / 2022-10-20

    • fix(update): handle runValidators when using $set on a doc array in discriminator schema #12571 #12518
    • fix(document): allow creating document with document array and top-level key named schema #12569 #12480
    • fix(cast): make schema-level strictQuery override schema-level strict for query filters #12570 #12508
    • fix(aggregate): avoid adding extra $match stage if user manually set discriminator key to correct value in first pipeline stage #12568 #12478
    • fix: Throws error when updating a key name that match the discriminator key name on nested object #12534 #12517 lpizzinidev
    • fix(types): add limit to $filter expression #12553 raphael-papazikas
    • fix(types): correct replaceWith type pipeline stage #12535 FabioCingottini
    • fix(types): add missing densify type pipeline type #12533 FabioCingottini
    • docs(populate): added transform option description #12560 #12551 lpizzinidev
    • docs(connection): add sample to useDb() documentation #12541 lpizzinidev
    • docs(guide): update broken read-preference links #12538 #12525 hasezoey
    • chore: add TypeScript version field to issue template #12532 hasezoey
    Source code(tar.gz)
    Source code(zip)
  • 6.6.5(Oct 5, 2022)

    6.6.5 / 2022-10-05

    • fix(document): set defaults on subdocuments underneath init-ed single nested subdocument #12523 #12515
    • fix: make Jest fake timers check more robust to other libs that overwrite time functions #12527 #12514
    • fix(types): indicate that Schema.prototype.discriminator() returns this #12522 #12457
    • fix(types): add "estimatedDocumentCount" and "countDocuments" as possible hooks #12519 #12516
    • docs(models): add section on MongoDB Views #12526 #5694
    • docs(subdocs): clarify that populated docs are not subdocs #12521 #12398
    • docs(change-streams): remove unnecessary obsolete comment about needing to use mongodb driver change streams #12444
    Source code(tar.gz)
    Source code(zip)
  • 6.6.4(Oct 3, 2022)

    6.6.4 / 2022-10-03

    • fix(model): avoid saving applied defaults if path is deselected #12506 #12414
    • fix(types): correct DocType for auto typed query helpers #12342
    • fix(types): avoid "excessively deep" type instantiation error when using bulkWrite() with type that extends from document #12277
    • fix(types): avoid relying on typeof this, which isn't supported in TypeScript < 4.4 #12375
    • docs(schema): correct example for Schema.prototype.discriminator() #12493
    • docs(typescript): clean up query helpers examples #12342
    • chore: use mongodb-memory-server for testing #12262 hasezoey
    Source code(tar.gz)
    Source code(zip)
  • 6.6.3(Sep 30, 2022)

    6.6.3 / 2022-09-30

    • fix(query): treat findOne(_id) as equivalent to findOne({ _id }) #12485 #12325
    • fix(timestamps): findOneAndUpdate creates subdocs with timestamps in reverse order #12484 #12475 lpizzinidev
    • fix(types): make schema.plugin() more flexible for schemas that don't define any generics #12486 #12454
    • fix(types): add "array of array key-value pairs" as a argument option for "query.sort()" #12483 #12434 hasezoey
    • fix(types): remove unused defaults in "PluginFunction" #12459 hasezoey
    • fix(types): update DiscriminatorSchema to have better names and combine statics #12460 hasezoey
    Source code(tar.gz)
    Source code(zip)
  • 6.6.2(Sep 26, 2022)

    6.6.2 / 2022-09-26

    • fix(model): avoid deleting shared schema methods in fix for #12254 #12423
    • fix(document): set $inc default value in case field has not been specified on the document #12435 lpizzinidev
    • fix(query): handle select: false on map paths in query results #12467 lpizzinidev
    • fix(types): add HydratedDocumentFromSchema to make it easier to pull inferred hydrated doc type #12464 #12319
    • fix(types): add sanitizeFilter to types #12465 zrosenbauer
    • fix(types): infer number enum types from schema if using enum: [0, 1] as const #12463 #12242
    • docs(validation): add section on global schematype validation, clean up other issues #12430
    • docs: add clarification about overwrite flag in model.js #12447 Tzvika-m
    • docs: change to consistent "Example:" for jsdoc comments #12432 hasezoey
    Source code(tar.gz)
    Source code(zip)
  • 6.6.1(Sep 14, 2022)

    6.6.1 / 2022-09-14

    • fix: correctly apply defaults after subdoc init #12328
    • fix(array): avoid using default _id when using pull() #12294
    • fix: allow null values inside $expr objects #12429 MartinDrost
    • fix(query): use correct Query constructor when cloning query #12418
    • docs(website): remove setting "latest38x" which is not used anywhere #12396 hasezoey
    Source code(tar.gz)
    Source code(zip)
  • 6.6.0(Sep 8, 2022)

    6.6.0 / 2022-09-08

    • feat: upgrade mongodb driver -> 4.9.1 #12370 AbdelrahmanHafez
    • feat: re-export default Mongoose instance properties for ESM named imports support #12256
    • feat(model): add option to skip invalid fields with castObject() #12156 IslandRhythms
    • feat: use setPrototypeOf() instead of proto to allow running on Deno #12315
    • feat(QueryCursor): add support for AbortSignal on eachAsync() #12323
    • feat(types): add types for new $densify operator #12118 IslandRhythms
    Source code(tar.gz)
    Source code(zip)
  • 6.5.5(Sep 7, 2022)

    6.5.5 / 2022-09-07

    • fix(setDefaultsOnInsert): avoid applying defaults on insert if nested property set #12279
    • fix(model): make applyHooks() and applyMethods() handle case where custom method is set to Mongoose implementation #12254
    • fix(types): add string "ascending" and "descending" index-directions #10269
    • docs: upgrade dox to 1.0.0 #12403 hasezoey
    • docs: update old mongodb nodejs driver documentation urls #12387 hasezoey
    • docs: update JSDOC ... (spread) definition #12388 hasezoey
    • refactor(model): allow optionally passing indexes to createIndexes and cleanIndexes #12280 AbdelrahmanHafez
    Source code(tar.gz)
    Source code(zip)
  • 6.5.4(Aug 30, 2022)

    6.5.4 / 2022-08-30

    • fix(document): allow calling $assertPopulated() with values to better support manual population #12233
    • fix(connection+mongoose): better handling for calling model() with 1 argument #12359
    • fix(model): allow defining discriminator virtuals and methods using schema options #12326
    • fix(types): fix MongooseQueryMiddleware missing "findOneAndReplace" and "replaceOne" #12330 #12329 Jule- lpizzinidev
    • fix(types): fix replaceOne return type #12351 lpizzinidev
    • fix(types): use this for return type from $assertPopulated() #12234
    • docs: highlight how to connect using auth in README #12354 AntonyOnScript
    • docs: improve jsdoc comments for private methods #12337 hasezoey
    • docs: fix minor typo in compatibility table header #12355 skyme5
    Source code(tar.gz)
    Source code(zip)
  • 6.5.3(Aug 25, 2022)

    6.5.3 / 2022-08-24

    • fix(document): handle maps when applying defaults to nested paths #12322
    • fix(schema): make ArraySubdocuments apply _id defaults on init #12264
    • fix(populate): handle specifying recursive populate as a string with discriminators #12266
    • perf(types): remove extends Query in Schema.pre() and Schema.post(), loosen discriminator() generic #10349
    • perf(types): some more micro-optimizations re: #10349, remove extra type checking on $ne, etc.
    • fix(types): infer schema on connection.model() #12298 #12125 hasezoey
    • fix(types): add missing findById() type definitions #12309 lpizzinidev
    • fix(types): allow $search in $lookup pipeline stages for MongoDB v6.x support #12278 AbdelrahmanHafez
    • fix(types): add parameter "options" to "Model.remove" #12258 hasezoey
    • fix(types): sync single-generic-no-constraint "model" between "index.d.ts" and "connection.d.ts" #12299 hasezoey
    • fix(types): update isDirectModified typing #12290 gabrielDonnantuoni
    • docs: update links on api docs #12293 eatmoarrice
    • docs: add note about language_override option #12310 IslandRhythms
    • docs(document): add "String[]" to Document.depopulate as jsdoc parameter type #12300 hasezoey
    • docs: update Node.js EventEmitter url #12303 rainrisa
    Source code(tar.gz)
    Source code(zip)
  • 6.5.2(Aug 10, 2022)

    6.5.2 / 2022-08-09

    • fix(aggregate): avoid throwing error when disconnecting with change stream open #12201 ramos-ph
    • fix(query): overwrite top-level key if using Query.prototype.set() to set to undefined #12155
    • fix(query): shallow clone options before modifying #12176
    • fix(types): auto schema type inference on Connection.prototype.model() #12240 hasezoey
    • fix(types): better typescript support for schema plugins #12139 emiljanitzek
    • fix(types): make bulkWrite() type param optional #12221 #12212
    • docs: misc cleanup #12199 hasezoey
    • docs: highlight current top-most visible header in navbar #12222 hasezoey
    • docs(populate): improve examples for Document.prototype.populate() #12111
    • docs(middleware): clarify document vs model in middleware docs #12113
    Source code(tar.gz)
    Source code(zip)
  • 6.5.1(Aug 3, 2022)

    6.5.1 / 2022-08-03

    • fix(timestamps): set timestamps on child schema when child schema has timestamps: true but parent schema does not #12119
    • fix(schema+timestamps): handle insertMany() with timestamps and discriminators #12150
    • fix(model+query): handle populate with lean transform that deletes _id #12143
    • fix(types): allow $pull with _id #12142
    • fix(types): add schema plugin option inference #12196 hasezoey
    • fix(types): pass type to mongodb bulk write operation #12167 emiljanitzek
    • fix(types): map correct generics from model to schema #12125 emiljanitzek
    • fix(types): avoid baffling circular reference when using PopulatedDoc with a bidirectional reference #12136
    • fix(types): allow using path with $count #12149
    • docs(compatibility): change to use a table #12200 hasezoey
    • docs(api_split.pug): add "code" to sidebar entries #12153 hasezoey
    • docs: add "code" to Headers (and index list) #12152 hasezoey
    Source code(tar.gz)
    Source code(zip)
  • 6.5.0(Jul 26, 2022)

    6.5.0 / 2022-07-26

    • perf(document): avoid creating unnecessary empty objects when creating a state machine #11988
    • feat: upgrade mongodb driver -> 4.8.1 #12103 AbdelrahmanHafez
    • feat(model): allow passing timestamps option to Model.bulkSave(...) #12082 AbdelrahmanHafez
    • feat(model): add castObject() function that casts a POJO to the model's schema #11945
    • feat(document): add $inc() helper that increments numeric paths #12115
    • feat(schema): add schema level lean option IslandRhythms
    • feat(schema): add global id option to disable id on schemas #12067 IslandRhythms
    • fix(connection): re-run Model.init() if re-connecting after explicitly closing a connection #12130
    • feat(model): add applyDefaults() helper that allows applying defaults to document or POJO #11945
    • feat(model): allow calling hydrate() with { setters: true } #11653
    • feat(model): add hydrate option to Model.watch() to automatically hydrate fullDocument #12121
    • feat(types): add support for automatically typed virtuals in schemas #11908 mohammad0-0ahmad
    Source code(tar.gz)
    Source code(zip)
  • 6.4.7(Jul 25, 2022)

    6.4.7 / 2022-07-25

    • fix(virtualtype): use $locals for default virtual getter/setter rather than top-level doc #12124
    • fix(document): call subdocument getters if child schema has getters: true #12105
    • fix(schematype): actually always return "this" where specified #12141 hasezoey
    • fix(types): correct return value for Model.exists() #12094
    • docs(guides): add link to advanced schemas doc #12073
    • docs: handle @see in jsdoc #12144 hasezoey
    • docs: make use of the deprecated tag available in jsdoc for documentation #12080 hasezoey
    • docs(api_split): add basic DEPRECATED output #12146 hasezoey
    • docs: various jsdoc cleanup #12140 hasezoey
    • docs(api_split.pug): add "code" to parameter name #12145 hasezoey
    Source code(tar.gz)
    Source code(zip)
  • 6.4.6(Jul 20, 2022)

    6.4.6 / 2022-07-20

    • fix(schema): disallow setting proto when creating schema with dotted properties #12085
    • fix(document): avoid mutating original object passed to $set() when applying defaults to nested properties #12102
    • fix(query): apply lean transform option to top-level document #12093
    • docs(migrating_to_6): correct example for isObjectIdOrHexString() #12123 LokeshKanumoori
    Source code(tar.gz)
    Source code(zip)
  • 6.4.5(Jul 18, 2022)

    6.4.5 / 2022-07-18

    • fix(model+timestamps): set timestamps on subdocuments in insertMany() #12060
    • fix: correct isAtlas check #12110 skrtheboss
    • fix(types): fix various issues with auto typed schemas #12042 mohammad0-0ahmad
    • fix(types): allow any value for AddFields #12096
    • fix(types): allow arbitrary expressions for ConcatArrays #12058
    • fix(types): make $addToSet fields mutable to allow programatically constructing $addToSet #12091
    • fix(types): add $let as a possible expression to $addFields #12087 AbdelrahmanHafez
    • fix(types): fix $switch expression type #12088 AbdelrahmanHafez
    • fix(types): correct options type for syncIndexes() #12101 lpizzinidev
    • fix(types): avoid treating | undefined types as any in Require_id to better support _id: String with auto-typed schemas #12070
    • docs: fix up various jsdoc issues #12086 hasezoey
    • docs: add sanitizeFilter to mongoose.set() options #12112 pathei-kosmos
    Source code(tar.gz)
    Source code(zip)
  • 6.4.4(Jul 8, 2022)

    6.4.4 / 2022-07-08

    • fix(types): allow using an object to configure timestamps #12061 lantw44
    • fix(types): support findOneAndReplace with rawResult #12062 lantw44
    • docs: upgrade API documentation parser #12078 #12072 #12071 #12024 hasezoey
    • docs(document): add more info on $isNew #11990
    • docs: add SchemaType doValidate() to docs #12068
    Source code(tar.gz)
    Source code(zip)
  • 6.4.3(Jul 5, 2022)

    6.4.3 / 2022-07-05

    • fix(document): handle validating deeply nested subdocuments underneath nested paths with required: false #12021
    • fix(types): infer schematype type from schema paths when calling SchemaType.path() #11987
    • fix(types): add $top and $topN aggregation operators #12053
    • fix(types): clean up a couple of issues with $add and $ifNull #12017
    • fix(types): allow $cond with $in #12028
    • docs: add path level descending index example in docs #12023 MitchellCash
    • docs: add Buffer, Decimal128, Map to docs #11971
    Source code(tar.gz)
    Source code(zip)
  • 6.4.2(Jul 1, 2022)

    6.4.2 / 2022-07-01

    • fix: keep autoIndex & autoCreate as true by default if read preference is primaryPreferred #11976
    • fix(types): improve inferred Schema Type to handle nested paths and ObjectIds #12007 iammola
    • fix(types): avoid inferring doc type from param to create() #12001
    • fix(types): make populate Paths generic consistently overwrite doc interface #11955
    • fix(types): allow null at ne expression second parameter #11996 jyeros
    • fix(types): change index "weights" to be more explicit #11997 hasezoey
    Source code(tar.gz)
    Source code(zip)
  • 6.4.1(Jun 27, 2022)

    6.4.1 / 2022-06-27

    • fix(schema): allow 0 for numbers if required and ref both set #11912
    • fix(query): skip applying default projections over slice projections #11940
    • fix(types): handle arrays in ApplyBasicQueryCasting correctly #11964
    • fix(types): fix $match typings #11969 andreialecu
    • fix(types): avoid adding non-existent properties from model constructor for typegoose #11960
    • fix(types): make Mongoose UpdateQuery compatible with MongoDB UpdateFilter #11911
    • fix(types): simplify MergeType constraints #11978
    • fix(types): correct references to Buffer for @types/node >= 16.0.0 < 16.6.0 #11963
    • fix(types): re-add the possibility to pass undefined for projection in Model.find #11965 ghost91-
    • fix(types): fix typo for indexes #11953 AbdelrahmanHafez
    • fix(document+types): document merge option #11913
    • docs: update schematypes.md #11981 korzio
    • docs: update validation.md #11982 korzio
    Source code(tar.gz)
    Source code(zip)
Owner
Automattic
We are passionate about making the web a better place.
Automattic
🍉 Reactive & asynchronous database for powerful React and React Native apps ⚡️

A reactive database framework Build powerful React and React Native apps that scale from hundreds to tens of thousands of records and remain fast ⚡️ W

Nozbe 8.8k Jan 5, 2023
Yaade is an open-source, self-hosted, collaborative API development environment.

Yaade - Yet Another API Development Environment Yaade is an open-source, self-hosted, collaborative API development environment. ?? Why did you develo

null 1k Dec 28, 2022
Object Relational Mapping

Object Relational Mapping This package is not actively maintained If you're starting a new project, please consider using one of the following instead

Diogo Resende 3.1k Dec 14, 2022
In-memory Object Database

limeDB What is LimeDB LimeDB is object-oriented NoSQL database (OOD) system that can work with complex data objects that is, objects that mirror those

Luks 2 Aug 18, 2022
A simple, fast, reliable Object Relationship Manager for Bun.

Burm is an object relational manager for Bun, the fastest Javascript Engine. The name is a merge of "Bun" and "ORM", forming "Burm". Pronounce it howe

William McGonagle 70 Dec 28, 2022
A query builder for PostgreSQL, MySQL and SQLite3, designed to be flexible, portable, and fun to use.

knex.js A SQL query builder that is flexible, portable, and fun to use! A batteries-included, multi-dialect (MSSQL, MySQL, PostgreSQL, SQLite3, Oracle

knex 16.9k Jan 4, 2023
Azure Data Studio is a data management tool that enables you to work with SQL Server, Azure SQL DB and SQL DW from Windows, macOS and Linux.

Azure Data Studio is a data management tool that enables working with SQL Server, Azure SQL DB and SQL DW from Windows, macOS and Linux.

Microsoft 7k Dec 31, 2022
Fast and advanced, document based and key-value based NoSQL database that able to work as it is installed.

About Fast and advanced, document based and key-value based NoSQL database that able to work as it is installed. Features NoSQL database Can be run as

null 6 Dec 7, 2022
O Projeto RENOVA é um e-commerce que visa ajudar no contato de pessoas interessadas em reciclagem com os itens de potencial reciclavel. Work in progress.

Descrição Nest framework TypeScript starter repository. Instalação $ npm install Rodando o app # development $ npm run start # watch mode $ npm run s

RENOVA 12 Dec 15, 2022
The Official MongoDB Node.js Driver

MongoDB NodeJS Driver The official MongoDB driver for Node.js. NOTE: v3.x released with breaking API changes. You can find a list of changes here. Ver

mongodb 9.6k Dec 28, 2022
🍹 MongoDB ODM for Node.js apps based on Redux

Lightweight and flexible MongoDB ODM for Node.js apps based on Redux. Features Flexible Mongorito is based on Redux, which opens the doors for customi

Vadim Demedes 1.4k Nov 30, 2022
A high performance MongoDB ORM for Node.js

Iridium A High Performance, IDE Friendly ODM for MongoDB Iridium is designed to offer a high performance, easy to use and above all, editor friendly O

Sierra Softworks 570 Dec 14, 2022
The ultimate solution for populating your MongoDB database.

Mongo Seeding The ultimate solution for populating your MongoDB database ?? Define MongoDB documents in JSON, JavaScript or even TypeScript files. Use

Paweł Kosiec 494 Dec 29, 2022
📇 Generates and parses MongoDB BSON UUIDs

uuid-mongodb Generates and parses BSON UUIDs for use with MongoDB. BSON UUIDs provide better performance than their string counterparts. Inspired by @

Carmine DiMascio 96 Nov 21, 2022
A MongoDB-like database built on top of Hyperbee with support for indexing

hyperbeedeebee A MongoDB-like database built on top of Hyperbee with support for indexing WIP: There may be breaking changes in the indexing before th

null 35 Dec 12, 2022
E-Commerce Application developed with nodejs and stored to mongodb.

E-Commerce Application This Application has been developed with nodejs and mongodb. Environment Variables Create a file named config.env in config dir

Abdullah Öztürk 13 Dec 23, 2021
Database manager for MySQL, PostgreSQL, SQL Server, MongoDB, SQLite and others. Runs under Windows, Linux, Mac or as web application

Database manager for MySQL, PostgreSQL, SQL Server, MongoDB, SQLite and others. Runs under Windows, Linux, Mac or as web application

DbGate 2k Dec 30, 2022
A back-end server aplication created using node.js, express and mongodb.

Course Material and FAQ for my Complete Node.js, Express and MongoDB Bootcamp This repo contains starter files and the finished project files for all

Pablo César Jiménez villeda 1 Jan 4, 2022
5-BackControlFinanzas - Node & MongoDB

API para APP 'Control Finanzas' Pequeña API/Backend creada para la aplicacion personal de Control Finanzas. Enlace de github a la aplicacion que requi

Ignacio Tirado 1 Jan 3, 2022