Connections
An application can only connect up to one database in such a way, mongoose.connection
Obtain a database connection
var mongoose = require('mongoose');
var db = mongoose.connection;
db.once('open', function () {
console.log('connect mongodb successful...');
});
db.on('error', function (err) {
console.error('err', err);
});
mongoose.connect('mongodb://localhost:27017/Lyf');
An application can connect multiple databases in such a way, mongoose.createConnection
returns the database connection
var mongoose =require('mongoose');
var db1=mongoose.createConnection('mongodb://localhost:27017/Lyf');
var db2=mongoose.createConnection('mongodb://localhost:27017/blog');
db1.once('open', function () {
console.log('connect Lyf mongodb successful...');
});
db1.on('error', function (err) {
console.error('err', err);
});
db2.once('open', function () {
console.log('connect blog mongodb successful...');
});
db2.on('error', function (err) {
console.error('err', err);
});
Schema
Types when building schema:Number
[]
{}
String
Boolean
ObjectId
Mixed
Schema
Buffer
Schema.methods.fn
can used by instance of Model
Schema.statics.fn
can used by Schema
Schema.virtual('vName').get(fn)
,
Schema.virtual('vName').set(fn)
invalidate
validate data legality, enum:[]
min
max
required:true
validate:[fn,'errMes']
unique:true
var mongoose =require('mongoose');
var Schema=mongoose.Schema;
options={
autoIndex: false,//Default true, indexes are added automatically
strict: false,//Default true, Strictly check the data
capped: 100,//Operational data limit
versionKey: '_name',// Version lock, the default _v
collection: 'name'//The name of the collection in the database
}
var IphoneSchema=new Schema({
iphone:Number
});
var UserSchema=new Schema({
name:{type:String,validate:[function(value){
if(value.lenght<2)
return false
else
return true
},'path name field Invalid']},
age:{type:Number,min:0},
teen:Boolean,
interesting:Schema.Types.Mixed,
id_card:{type:Schema.Types.ObjectId,required:true},
child:[Schema.Types.ObjectId],
location:{
country:{type:String,enum:['china','us']},
province:String,
city:String
},
iphone:IphoneSchema,
file:Buffer
},options);
UserSchema.methods = {
say: function () {
console.log(`say->${this.name}`);
}
}
UserSchema.statics = {
say: function () {
console.log(`say static`);
}
}
UserSchema.virtual('basicInfo').get(function () {
return this.name + ',' + this.age;
});
UserSchema.virtual('basicInfo').set(function (value) {
var split = value.split(',');
this.name = split[0];
this.age = split[1];
});
model
compiling model by db.model('name',Schema)
use the instance of model -> save
use the Model class static -> create
, can insert multi doc by once
var mongoose = require('mongoose');
var db = mongoose.connection;
db.once('open', function () {
console.log('connect mongodb successful...');
});
db.on('error', function (err) {
console.error('err', err);
});
mongoose.connect('mongodb://localhost:27017/Lyf');
var UserSchema = new mongoose.Schema({
name: String
})
UserModel = db.model('user', UserSchema)
new UserModel({name: 'Lyf'}).save((err)=> {
if (!err)
console.log('ok')
})
UserModel.create([{name:'L'},{name:'yf'}],(err)=>{
if (!err)
console.log('ok')
})
Middleware
ps:The following is the middleware I used
pre
is used before save
or remove
post
is used after save
or remove
Schema.pre('save',function(next){
//...
next();
})
Schema.post('save',function(doc){
//...
})
populate
populate(options)
options={ path
match
select
options
}
there are no joins in MongoDB,so use populate+ref
var mongoose = require('mongoose');
var db = mongoose.connection;
db.once('open', function () {
console.log('connect mongodb successful...');
});
db.on('error', function (err) {
console.error('err', err);
});
mongoose.connect('mongodb://localhost:27017/Lyf');
var BookSchema = new mongoose.Schema({
_id: Number,//`@ _id:Number一致`
title: String
});
var UserSchema = new mongoose.Schema({
name: String,
i_book: {type: Number, ref: 'book'}//`@book` `@Number`
})
UserModel = db.model('user', UserSchema);
BookModel = db.model('book', BookSchema);//`@book一致`
UserModel
.findOne({name: 'Lyf'})
.populate({path: 'i_book', select: {title: 1}, match: {title: '1001的世界'}})
.exec(function (err, docs) {
console.log(docs);
});
Inline Array
As long as auth = Lyf or age = 24 {} in the array returns the doc
LModel.findOne({'names.auth': 'Lyf', 'names.age': 24}, {names: 1, _id: 0}, function (err, docs) {});
As long as auth=Lyf and age=23 in the array returns the doc
LModel.findOne({names: {$elemMatch: {auth: 'Lyf', age: 23}}}, {}, function (err, docs) {});
Inserts a record into the array of doc
LModel.update({}, {$push: {names: {auth: 'Wtl', age: 23}}}, {multi: true}, function (err, count) {});
Removes the matching record from the array of doc
LModel.update({}, {$pull: {names: {age: 23}}}, function (err, count) {})
Insert a unique record into the array of doc
LModel.update({}, {$addToSet: {names: {auth: 'Lyf', age: 23}}}, function (err, count) {});
Removes a record from the header (1) or trailer (-1) of the array in the document
LModel.update({}, {$pop: {names: -1}}, function (err, count) {})
Update a record in the document array .$. as a locator
LModel.update({'names.auth': 'Lyf'}, {$set: {'names.$.age': 24}}, function (err, count) {})
Frequently used keywords
find
update
remove
count
gt
gte
lt
lte
ne
set
limit
skip
sort
exists
elemMatch
in
nin
and
or
size
multi
upsert