Recently, I have been using Express +Mongoose. For the convenience of future query and summary of questions, I will simply record them here

Installation and linking


npm install mongoose 
Copy the code

Basic concepts of Mongoose


Schema: table definition template

Model: Similar to a relational database table, encapsulated as an object with some collection operations

let schema = new mongoose.Schema({
    id: {
        type: Number,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    age: {
        type: Number
    }
}, {
    versionKey: false,
    timestamps: {
        createdAt: 'createTime', updatedAt: 'updateTime', lastLoginDate: 'lastLoginDate'}});let userModel = mongoose.model('user', schema);
Copy the code

Commonly used API


When it comes to database, the first thing that comes to mind is to add, delete, change and check.

new

Model.create(): Inserts one or more documents

Model.create(docs[, options][, callback])

If you insert a document, pass in an object; If multiple documents are inserted, an array is passed in

let doc = {
    id: 1,
    name: 'shan-er',
    age: 1
};
userModel.create(doc, (error) => {})
Copy the code
Modelentity.save (): For the current document instance only

Document.prototype.save([options][, callback])

let doc = {
    id: 1,
    name: 'shan-er',
    age: 1
};
let mongooseEntity = new userModel(doc);
mongooseEntity.save((error) => {})
Copy the code
Model.insertMany()

Model.insertMany(docs[, options][, callback])

Multiple data inserts. Inserting multiple data at once is faster than using the create loop.

Mongoose validates each document before sending insertMany to MongoDB. Therefore, if a document has a validation error, no documents will be saved unless the Ordered option is set to false.

let docs = [{
    id: 1,
    name: 'shan-er',
    age: 1
}, {
    id: 2,
    name: 'shan-er-2',
    age: 1
}];
userModel.insertMany(docs, (error, docs) => {})
Copy the code
Create () differs from save()

Model.create() calls the <model_instance>.save() method internally and does some extra wrapping.

The main differences between the two are:

  • Model.create() can hold a set of documents simultaneously.

  • .save() is for the current document instance only.

Create (docs) executes MyModel(doc).save() for each document in docs.

To find the

Model.find()

Model.find(conditions, [fields], [options], [callback])

Usermodel. find({age: 1}, (err, docs) => {// docs is the result array}) userModel.find({}, [err, docs) => {// docs is the result array}) userModel.find({}, ['id'.'name'], (err, docs) => {// docs now contains only some key values of the document})Copy the code
Model.findOne()

Model.findOne([conditions], [projection], [options], [callback])

Same as model.find, but returns a single document

Usermodel.findone ({age: 1}, (err, doc) => {// doc is a single document})Copy the code
Model.findById()

Model.findById(id, [projection], [options], [callback])

Same as findOne, but it takes the _id of the document as an argument and returns a single document. The _ID can be a string or an ObjectId object.

Usermodel.find (obj._id, (err, doc) => {// doc is a single document})Copy the code

Modify the

Model.Update()

Model.update(conditions, doc, [options], [callback])

Conditions: query conditions; Doc: indicates the data to be modified. The primary key (_id) cannot be modified. Options: control options.

The method will match the content searched for update, return the number of data processing;

userModel.update({name: 'shan-er'}, {$set : {age : 2}, {upsert : true}, (err) => {})
Copy the code
Model.findOneAndUpdate()

Model.findOneAndUpdate([conditions], [update], [options], [callback])

The method updates the database based on the lookup and returns the processed data

FindOneAndUpdate () to get the data, just modify the data and don’t care about the modified data update()

Model.findByIdAndUpdate()

Model.findByIdAndUpdate(id, [update], [options], [callback])

Model.updatemany (): Updates multiple files at once

Model.updateMany(conditions, doc, [options], [callback])

Model.updateone (): Updates one at a time

Model.updateOne(conditions, doc, [options], [callback])

The options that
Options The following options are available: new: bool - The default value is false. Returns the modified data. Upsert: bool - Default false. If it does not exist, create a record. Fields: {Object | String} - select field. Similar. Select (fields). FindOneAndUpdate (). MaxTimeMS: Query time upper limit. Sort: If there are more than one query criteria, the query is updated in order. RunValidators: If the value is true, perform Validation. SetDefaultsOnInsert: If the upsert option is true, insert the default values defined by the document on new creation. PassRawResult: If true, the original result is used as the third argument to the callback function.Copy the code
.save() and update()
  1. Update is more efficient than save() after find because you don’t have to read the entire document.
  2. Mongoose’s update is MongoDB’s update, but Mongoose’s save may be MongoDB’s insert or update.
  3. For Save, Mongoose will automatically diff new documents and only change the updated parts. This is good for atomicity.
  4. Update does not trigger middleware, and Validation does not by default, but can be modified.

delete

Model.remove()

Model.remove(conditions[, options][, callback])

The remove method can be used in two ways, one on models and the other on model instances.

Delete all documents that match the conditions condition from the collection

Model.findOneAndRemove()

Model.findOneAndRemove(conditions[, options][, callback])

Model.findByIdAndRemove()

Model.findOneAndRemove(id[, options][, callback])

Model.deleteOne()

Model.deleteOne(conditions[, options][, callback])

Delete the first document that meets the conditions.

Model.deleteMany()

Model.deleteMany(conditions[, options][, callback])

Delete all documents that meet the conditions.

Remove and deleteMany

Same effect, different return value.

Remove () doesn’t really free up space. The DB.RepairDatabase () needs to continue to reclaim disk space.

DeleteOne (), deleteMany()

FAQ Summary


Objects obtained with Mongoose cannot have attributes added

The reason:

Because Mongoose is an ODM (Object Document Mapper), similar to the OPERATION of Relational databases using ORM(Object Relational Mapper), The structure of the data we obtained using Mongoose depends on the schema structure we defined. The added attribute is not defined in the schema, so it is invalid to add an attribute to the result.

Method 1: Add attributes to the Schema

Add attribute: one is to directly add attribute value, into the library; If you do not want to enter the library, you can use the virtual attribute

schema.virtual('fullName').get(function () {
  returnthis.firstName + this.lastName; }); // 1. Doc._doc. fullName // 2.'toObject', {virtuals: true});
// userModel.set('toJSON', {virtuals: true});
Copy the code

Method 2: Clone results

Example slightly.

Automatically add “s” to the collection name?

Official website Definition API

The collection name should be the third parameter. By default, a collection is automatically generated in the plural form based on the value of the parameter name

let userModel = mongoose.model('user', schema, 'user');
Copy the code
summary

There are many related operations of Mongoose, which will not be listed in detail here. As for the common problems, they may be updated at any time, so make a record ~