ChatGPT解决这个技术问题 Extra ChatGPT

Difference between MongoDB and Mongoose

I wanted to use the mongodb database, but I noticed that there are two different databases with either their own website and installation methods: mongodb and mongoose. So I came up asking myself this question: "Which one do I use?".

So in order to answer this question I ask the community if you could explain what are the differences between these two? And if possible pros and cons? Because they really look very similar to me.


Z
ZeMoon

I assume you already know that MongoDB is a NoSQL database system which stores data in the form of BSON documents. Your question, however is about the packages for Node.js.

In terms of Node.js, mongodb is the native driver for interacting with a mongodb instance and mongoose is an Object modeling tool for MongoDB.

mongoose is built on top of the mongodb driver to provide programmers with a way to model their data.

EDIT: I do not want to comment on which is better, as this would make this answer opinionated. However I will list some advantages and disadvantages of using both approaches.

Using mongoose, a user can define the schema for the documents in a particular collection. It provides a lot of convenience in the creation and management of data in MongoDB. On the downside, learning mongoose can take some time, and has some limitations in handling schemas that are quite complex.

However, if your collection schema is unpredictable, or you want a Mongo-shell like experience inside Node.js, then go ahead and use the mongodb driver. It is the simplest to pick up. The downside here is that you will have to write larger amounts of code for validating the data, and the risk of errors is higher.


That's quite an opinion-based question. Some might prefer a lower-level API. Why don't you check out Mongoose and the native driver, and then decide which one is better for you?
@Michael9 The native MongoDB driver for Node.js has the same name. Please note the words 'in terms of Node.js...'. Your edit was incorrect.
One should also consider the performance factor, please refer to this url, this guy has shared awesome benchmarks.medium.com/@bugwheels94/…
If I install mongoose with npm, is mongodb also installed because it is a mongo base package? I cannot see this behaviour in package.json, but maybe under the hood mongodb is installed? Wait, here is the answer
@Timo correct, mongodb is a dependency for mongoose so it will be installed as well. However if you just use mongoose as a direct dependency for your project mongodb will not appear in package.json. You should however be able to see it inside node_modules.
N
Nemo

Mongo is NoSQL Database.

If you don't want to use any ORM for your data models then you can also use native driver mongo.js: https://github.com/mongodb/node-mongodb-native.

Mongoose is one of the orm's who give us functionality to access the mongo data with easily understandable queries.

Mongoose plays as a role of abstraction over your database model.


@ArslanRamay: medium.com/@bugwheels94/…, much helpful
This was originally run for the old Mongoose version and also not run as .lean() and instead returned as the entire object, not very comprehensive
Mongoose is an ODM (Object Document Mapper) and not an ORM (Object Relational Mapper).
R
Rahul

One more difference I found with respect to both is that it is fairly easy to connect to multiple databases with mongodb native driver while you have to use work arounds in mongoose which still have some drawbacks.

So if you wanna go for a multitenant application, go for mongodb native driver.


looks like mongoose has it natively to connect to multiple database. no need for workarounds stackoverflow.com/a/19475270/445600
d
dhaker

Mongodb and Mongoose are two different drivers to interact with MongoDB database.

Mongoose : object data modeling (ODM) library that provides a rigorous modeling environment for your data. Used to interact with MongoDB, it makes life easier by providing convenience in managing data.

Mongodb: native driver in Node.js to interact with MongoDB.


F
Forrest Wei

From the first answer,

"Using Mongoose, a user can define the schema for the documents in a particular collection. It provides a lot of convenience in the creation and management of data in MongoDB."

You can now also define schema with mongoDB native driver using

##For new collection

db.createCollection("recipes",
    validator: { $jsonSchema: {
         <<Validation Rules>>
        }
    }
)

##For existing collection

db.runCommand({
    collMod: "recipes",
    validator: { $jsonSchema: {
         <<Validation Rules>>
        }
    }
})
    

##full example

db.createCollection("recipes", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "servings", "ingredients"],
      additionalProperties: false,
      properties: {
        _id: {},
        name: {
          bsonType: "string",
          description: "'name' is required and is a string"
        },
        servings: {
          bsonType: ["int", "double"],
          minimum: 0,
          description:
            "'servings' is required and must be an integer with a minimum of zero."
        },
        cooking_method: {
          enum: [
            "broil",
            "grill",
            "roast",
            "bake",
            "saute",
            "pan-fry",
            "deep-fry",
            "poach",
            "simmer",
            "boil",
            "steam",
            "braise",
            "stew"
          ],
          description:
            "'cooking_method' is optional but, if used, must be one of the listed options."
        },
        ingredients: {
          bsonType: ["array"],
          minItems: 1,
          maxItems: 50,
          items: {
            bsonType: ["object"],
            required: ["quantity", "measure", "ingredient"],
            additionalProperties: false,
            description: "'ingredients' must contain the stated fields.",
            properties: {
              quantity: {
                bsonType: ["int", "double", "decimal"],
                description:
                  "'quantity' is required and is of double or decimal type"
              },
              measure: {
                enum: ["tsp", "Tbsp", "cup", "ounce", "pound", "each"],
                description:
                  "'measure' is required and can only be one of the given enum values"
              },
              ingredient: {
                bsonType: "string",
                description: "'ingredient' is required and is a string"
              },
              format: {
                bsonType: "string",
                description:
                  "'format' is an optional field of type string, e.g. chopped or diced"
              }
            }
          }
        }
      }
    }
  }
});

Insert collection Example

db.recipes.insertOne({
  name: "Chocolate Sponge Cake Filling",
  servings: 4,
  ingredients: [
    {
      quantity: 7,
      measure: "ounce",
      ingredient: "bittersweet chocolate",
      format: "chopped"
    },
    { quantity: 2, measure: "cup", ingredient: "heavy cream" }
  ]
});

A
ANK

If you are planning to use these components along with your proprietary code then please refer below information.

Mongodb:

It's a database. This component is governed by the Affero General Public License (AGPL) license. If you link this component along with your proprietary code then you have to release your entire source code in the public domain, because of it's viral effect like (GPL, LGPL etc) If you are hosting your application over the cloud, the (2) will apply and also you have to release your installation information to the end users.

Mongoose:

It's an object modeling tool. This component is governed by the MIT license. Allowed to use this component along with the proprietary code, without any restrictions. Shipping your application using any media or host is allowed.


Just thought I'd mention. The Server components before Oct 16th, 2018 were AGPL, but are now some custom license. although the driver (mongodb) was always Apache and never mattered for proprietary code. Ref: mongodb.com/community/licensing
The answer for MongoDB part 4 is incorrect. Generally client applications use the MongoDB drivers (i.e. MongoDB Node.JS driver) which are licensed under Apache v2. If you are modifying the MongoDB server code itself (the database) and redistributing it, then you either need a commercial agreement or open source it. The SSPL license change is just an addition for the database-as-a-service cloud vendors clause i.e. exposing the database features similar to MongoDB Atlas or AWS RDS, etc.
This isn't true. MongoDB the database itself isn't the same as the mongo driver.
Answer spreads FUD. It is wrongly accused AGPL and LGPL of a viral nature and claims that application which uses mongodb driver has to be released under GPL license. Mongoose uses mongodb driver and uses MIT. So the first part of the answer is a lie.
D
David

mongo-db is likely not a great choice for new developers.
On the other hand mongoose as an ORM (Object Relational Mapping) can be a better choice for the new-bies.


Welcome to Stack Overflow! Your answer might be valuable but it's missing some explanation. Perhaps you still can add some words to your answer. Here is a guide to give good answers.
Not really true; many would find it a lot easier to just use the native driver methods to access and manipulate data however they want than worry about schemas and all the other mongoose stuff.
A
Abdulhafeez Abdulraheem

Mongoose is built untop of mongodb driver, the mongodb driver is more low level. Mongoose provides that easy abstraction to easily define a schema and query. But on the perfomance side Mongdb Driver is best.


S
Secret

Mongodb and Mongoose are two completely different things!

Mongodb is the database itself, while Mongoose is an object modeling tool for Mongodb

EDIT: As pointed out MongoDB is the npm package, thanks!


mongodb isn't a database, it's a node package which is the native mongo driver. It's the lowest level API for accessing a mongo server from node js.
Question was regarding Mongodb native driver for db operations vs mongoose. Answer is not on point.
@mariocatch MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need. It is written on the homepage of its documentation.
Y
Yeshwin Verma The Programmer

MongoDB is The official MongoDB Node.js driver allows Node.js applications to connect to MongoDB and work with data. On the other side Mongoose it other library build on top of mongoDB. It is more easier to understand and use. If you are a beginner than mongoose is better for you to work with.