So it is Mongoose
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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.