Node.js driver MongoDB basic use tutorial
- 2021-01-18 06:15:23
- OfStack
Using mongoose allows us to better use the mongodb database without having to write tedious business logic.
The installation
npm install mongoose
Initial use
Before using mongoose, you need to install node and mongodb. The installation method of node and mongodb is not discussed here.
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var db = mongoose.connection;
mongoose.connect('mongodb://localhost/animal');
db.on('error', console.error);
db.once('open', function() {
// Patterns and models are built here
}
Quick start
In mongoose, all data is a schema, and each schema maps to an mongodb collection and defines the collection file structure.
// Set up here 1 All animals have all the attributes of this mode
var animalSchema = new Schema({
name: String,
age: Number,
});
Models are a variety of constructors that we define from Schema. Instans of models can use many operations. All document creation and retrieval is handled by the model
var animalMode = db.model('Animal', animalSchema);
Instance models are essentially files that can be easily created and modified
var cat = new animalMode({
name: 'catName',
age: '7', // I'm still using strings here, mongoose The type is automatically converted
});
cat.save(function(err, thor) {
if (err) return console.log(err);
console.log(thor);
});
// Or you can use create
//cat.create(function(err, thor) {
// if (err) return console.log(err);
// console.log(thor);
//});
// Perform a lookup
animalMode.find(function(err, people){
if(err) console.log(err);
console.log(people);
});
// Find the qualifying data
animalMode.findOne({title: 'catName'}, function(err, cat){
if(err) console.log(err);
console.log(cat);
});
Schema
The data type
This is all data types in Schema, including mongoose custom data types
String Number Date Buffer Boolean Mixed ObjectId ArrayUse of each data type
var animalMode = mongoose.model('Animal', schema);
var cat = new animalMode;
cat.name = 'Statue of Liberty' //String
cat.age = '7'; //Number
cat.updated = new Date; //Date
cat.binary = new Buffer(0); //Buffer
cat.living = false; //Boolean
cat.mixed = { any: { thing: 'i want' } }; //Mixed
cat._someId = new mongoose.Types.ObjectId; //ObjectId
cat.ofString.push("strings!"); //Array
Because Mixed does not define specific content, it can be used with {}. The following two definitions are equivalent.
var animalSchema = new Schema({any: {}});
var animalSchema = new Schema({any: {Schema.Types.Mixed}});
Custom method
You can bind methods to Schema
var animalSchema = new Schema({
name: String,
age: Number,
});
animalSchema.methods.findSimilarTypes = function (cb) {
return this.model('Animal').find({ name: this.name }, cb);
}
var animalMode = db.model('Animal', animalSchema);
cat.findSimilarTypes(function(err, cat){
if(err) console.log(err);
console.log(cat);
});
It is also possible to add static methods to Schema
animalSchema.statics.findByName = function (name, cb) {
return this.find({ name: new RegExp(name, 'i') }, cb);
}
var animalMode = db.model('Animal', animalSchema);
animalMode.findByName('catName', function (err, animals) {
console.log(animals);
});
The index
We can index mongodb data. mongodb supports two levels of indexing. In order to improve data lookup and location, it is necessary to build composite indexes
var animalSchema = new Schema({
name: String,
age: Number,
tags: { age: [String], index: true } // field level
});
animalSchema.index({ name: 1, age: -1 }); // schema level
However, this type of indexing can cause significant performance impacts. It is recommended to stop in production and set automatic indexing in setup mode to false disable
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var db = mongoose.connection;
mongoose.connect('mongodb://localhost/animal');
db.on('error', console.error);
db.once('open', function() {
// Patterns and models are built here
}
0
Model
C
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var db = mongoose.connection;
mongoose.connect('mongodb://localhost/animal');
db.on('error', console.error);
db.once('open', function() {
// Patterns and models are built here
}
1
R
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var db = mongoose.connection;
mongoose.connect('mongodb://localhost/animal');
db.on('error', console.error);
db.once('open', function() {
// Patterns and models are built here
}
2
U
The official documentation provides the update function Model.update
Model.update(conditions, doc, [options], [callback])
conditions update condition doc Update option update option safe (boolean) security mode, default option, value is true upsert (boolean) whether to create a new document if the condition does not match. The default value is false multi (boolean) Whether to update multiple files, the default value is false strict (boolean) is in strict mode with only one data update overwrite (boolean) overrides data, default to false callback err returns a value when data is updated in error numberAffected (I don't know) Number of rows affected in rawResponse
animalMode.update({name: 'catName'}, {age: '6'}, {multi : true}, function(err, numberAffected, raw){
if (err) return console.log(err);
console.log('The number of updated documents was %d', numberAffected);
console.log('The raw response from Mongo was ', raw);
});
D
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var db = mongoose.connection;
mongoose.connect('mongodb://localhost/animal');
db.on('error', console.error);
db.once('open', function() {
// Patterns and models are built here
}
4
other
// Returns the number of documents
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var db = mongoose.connection;
mongoose.connect('mongodb://localhost/animal');
db.on('error', console.error);
db.once('open', function() {
// Patterns and models are built here
}
5