mongoose 筆記

快速啟動

首先需要安裝MongoDB和Node.js。
然后使用npm下載mongoose:
npm install mongoose
接著我們直接在項目中引入mongoose,并且連接數據庫就會在本地運行 MongoDB了:

// index.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/demo');

用node命令執行index.js,demo數據庫就會在本地運行了。我們需要在連接數據庫成功或者失敗的時候有些提示,可以這樣添加代碼:

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {// 后續代碼默認都寫在這里!
});

連接成功的時候就會執行一次回調函數,現在假設下面所有代碼都是在成功的回調函數中的。

在Mongoose中,所有東西都是衍生自Schema。 Schema(模式)就像是Model(模型)的抽象類一樣的存在,創建一個Schema:

var mySchema =new mongoose.Schema({name: String
});

我們創建了一個叫mySchema的Schema,并且定義了一個屬性name,限定類型是String。接著可以用mySchema創建一個Model:

var MyModel = mongoose.model('MyModel', mySchema);

這樣就按照mySchema創建了一個MyModel模型,這個MyModel其實充當了兩個作用:

充當MongoDB中的collection(集合)
是用來構造document(文檔)的類
所以要構造一條document只要:

var  instance = new MyModel({ name: ' Instance' })
console.log( instance.name) // 'instance'

instance就是一條也可以稱作Document了。

如此看來Schema、Model和Document的關系就像是抽象類、實現類和實例三者的關系一樣。所以嘛,自然可以在Schema定義后添加方法:

var mySchema =new mongoose.Schema({name: String
});
mySchema.methods.getName=function(){console.log(this.name + "來自getName方法");
}
...instance.getName();//'instance來自getName方法'

instance實例現在還沒有被保存在MongoDB中,所有的實例都要調用save方法后才會保存進數庫:

instance.save((err,instance)=>{if (err) return console.error(err);instance.getName();
})

而后,需要查詢數據時就需要使用Model,因為Model的作用時充當MongoDB中的collection(集合),所以這樣查詢數據:

MyModel.find(function (err, instances) {if (err) return console.error(err);console.log(instances);
});

當然了,也可以加條件查詢:

MyModel.find({name:"instance"},callback);

這樣就是一個完整的使用mongoose插入和查詢數據的操作了。完整代碼如下:

var mongoose = require('mongoose');var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(callback) {var mySchema =new mongoose.Schema({name: String});mySchema.methods.getName = function() {console.log(this.name + "來自getName方法");}var MyModel = mongoose.model('MyModel', mySchema);var instance = new MyModel({ name: ' Instance' })console.log(instance.name) // 'instance'instance.getName(); //'instance'instance.save((err, instance) => {if (err) {return console.error(err) };instance.getName();})
});mongoose.connect('mongodb://localhost/test');

Schemas

定義schema

Mongoose所有的一切始于Schema。每一個Schema都映射到MongoDB中的collection(集合)和定義了document(文檔)的結構。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var blogSchema = new Schema({title:  String,author: String,body:   String,comments: [{ body: String, date: Date }],date: { type: Date, default: Date.now },hidden: Boolean,meta: {votes: Number,favs:  Number}
});

如果想要在創建Schema以后添加額外的key,可以使用Schema的add方法。

現在只需要知道SchemaTypes有:

String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array

創建了Schema后肯定就是創建Model了,然而,在這之間我們還可以定義instance方法、定義靜態Model方法、定義索引和使用生命周期掛鉤(中間件)

instance方法

instance方法使用schema的methods添加,這樣做可以讓創建的documents在save之前執行一些自定義的操作:

// define a schema
var animalSchema = new Schema({ name: String, type: String });// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function (cb) {return this.model('Animal').find({ type: this.type }, cb);
}//define a model
var Animal = mongoose.model('Animal', animalSchema);//instance
var dog = new Animal({ type: 'dog' });
dog.findSimilarTypes(function (err, dogs) {console.log(dogs); // woof
});

這樣做要注意的是不要重寫mongoose原來的document方法,不然會有未知錯誤。

靜態Model方法

在methods上添加的是給document用的,而在statics上添加的方法就是給Model用的:

// assign a function to the "statics" object of our animalSchema
animalSchema.statics.findByName = function (name, cb) {this.find({ name: new RegExp(name, 'i') }, cb);
}
var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function (err, animals) {console.log(animals);
});

索引

MongoDB支持使用索引。在mongoose中,分別可以在內部和外部定義,不過復合索引就只能在外部定義了:

var animalSchema = new Schema({name: String,type: String,tags: { type: [String], index: true } // 內部
});
animalSchema.index({ name: 1, type: -1 }); // 外部,復合索引

當應用啟動,Mongoose就會自動調用ensureIndex為每個schema創建索引。索引創建會有顯著的性能影響,所以建議在生產環境中禁用:

animalSchema.set('autoIndex', false);
// or
new Schema({..}, { autoIndex: false });

虛擬屬性

虛擬屬性是一種不會存儲進數據庫但是存在在doucment中的屬性。充當getter和setter的功能。
基本代碼:

var personSchema = new Schema({name: {first: String,last: String}
});
// compile our model
var Person = mongoose.model('Person', personSchema);
// create a document
var bad = new Person({name: { first: 'Walter', last: 'White' }
});

當調用toObject和toJSON方法時默認都是不會有虛擬屬性的。
現在想訪問bad.name.full就給出全名,就要使用虛擬屬性的getter功能:

personSchema.virtual('name.full').get(function () {return this.name.first + ' ' + this.name.last;
});。。。console.log('%s is insane', bad.name.full); // Walter White is insane

同樣的有setter功能:

personSchema.virtual('name.full').set(function (name) {var split = name.split(' ');this.name.first = split[0];this.name.last = split[1];
});
...
bad.name.full = 'Breaking Bad';
console.log(bad.name.first); // Breaking
console.log(bad.name.last);  // Bad

options

Schemas在構建實例或者通過set方法可以進行有options的配置:

new Schema({..}, options);
// 或者
var schema = new Schema({..});
schema.set(option, value);

options:

autoIndex:自動索引
capped
collection
id
_id
read
safe
shardKey
strict
toJSON
toObject
versionKey

autoIndex

在應用啟動時,Mongoose會調用ensureIndex為Schema構建索引。自Mongoose v3起,索引默認都會在后臺創建。如果想關閉自動創建或者以后手動創建索引,可以進行如下設置:

var schema = new Schema({..}, { autoIndex: false });
var Clock = mongoose.model('Clock', schema);
Clock.ensureIndexes(callback);

bufferCommands

capped

Mongoose支持MongoDB的固定大小集合,直接設置capped表示最大空間,單位時bytes,當然也可以使用對象設置max(最大document數)和autoIndexId:

new Schema({..}, { capped: 1024 });
//或者
new Schema({..}, { capped: { size: 1024, max: 1000, autoIndexId: true } });

collection

Mongoose中collection的名字默認時注冊Model時的名字,如果想要自定義,可以這樣設置:

var dataSchema = new Schema({..}, { collection: 'data' });

id

document都會設置一個虛擬屬性id并配置getter來獲取_id,如果不想要id虛擬屬性可以設為false:

// default behavior
var schema = new Schema({ name: String });
var Page = mongoose.model('Page', schema);
var p = new Page({ name: 'mongodb.org' });
console.log(p.id); // '50341373e894ad16347efe01'
// disabled id
var schema = new Schema({ name: String }, { id: false });
var Page = mongoose.model('Page', schema);
var p = new Page({ name: 'mongodb.org' });
console.log(p.id); // undefined

_id

Mongoose默認會在生成document的時候生成_id字段,如果想禁止這個行為可以設為false,但是插入數據庫的時候仍然會有_id字段:

// default behavior
var schema = new Schema({ name: String });
var Page = mongoose.model('Page', schema);
var p = new Page({ name: 'mongodb.org' });
console.log(p); // { _id: '50341373e894ad16347efe01', name: 'mongodb.org' }
// disabled _idvar schema = new Schema({ name: String }, { _id: false });
// 不要使用schema.set("_id",false),
var Page = mongoose.model('Page', schema);
var p = new Page({ name: 'mongodb.org' });
console.log(p); // { name: 'mongodb.org' }
// MongoDB 會在數據被插入的時候給_id
p.save(function (err) {if (err) return handleError(err);Page.findById(p, function (err, doc) {if (err) return handleError(err);console.log(doc); // { name: 'mongodb.org', _id: '50341373e894ad16347efe12' }})
})
read

設置讀寫分離屬性:

var schema = new Schema({..}, { read: 'primary' });            // also aliased as 'p'
var schema = new Schema({..}, { read: 'primaryPreferred' });   // aliased as 'pp'
var schema = new Schema({..}, { read: 'secondary' });          // aliased as 's'
var schema = new Schema({..}, { read: 'secondaryPreferred' }); // aliased as 'sp'
var schema = new Schema({..}, { read: 'nearest' });            // aliased as 'n'
safe
shardKey
strict

mongoose默認會開啟嚴格模式,所有不是在Schema定義的屬性都不會被保存進數據庫,將strict設為false就會:

var thingSchema = new Schema({..})
var Thing = mongoose.model('Thing', thingSchema);
var thing = new Thing({ iAmNotInTheSchema: true });
thing.save(); // iAmNotInTheSchema不會保存進數據庫// 設為 false..
var thingSchema = new Schema({..}, { strict: false });
var thing = new Thing({ iAmNotInTheSchema: true });
thing.save(); // iAmNotInTheSchema會保存進數據庫

還支持在instance的時候設置:

var thing = new Thing(doc, false); // 關閉嚴格模式

除了boolean,也可以設置為throw,但是這樣會拋出錯誤,而不時忽略值。
提示:不要手賤設為false
提示:在mongoose v2 默認只時false
提示:直接在document上set的只都不會被保存

var thingSchema = new Schema({..})
var Thing = mongoose.model('Thing', thingSchema);
var thing = new Thing({},false);
thing.iAmNotInTheSchema = true;
thing.save(); // iAmNotInTheSchema is never saved to the db

toJSON和toObject

兩個方法類似,都是輸出格式化對象:

var schema = new Schema({ name: String });
schema.path('name').get(function (v) {return v + ' is my name';
});//默認是不使用getter和不輸出virtual
schema.set('toJSON', { getters: true, virtuals: false });
var M = mongoose.model('Person', schema);
var m = new M({ name: 'Max Headroom' });console.log(m.toObject()); // { _id: 504e0cd7dd992d9be2f20b6f, name: 'Max Headroom' }console.log(m.toJSON()); // { _id: 504e0cd7dd992d9be2f20b6f, name: 'Max Headroom is my name' }// stringify內部會調用toJSON
console.log(JSON.stringify(m));//console內部時調用toObject
console.log(m);
versionKey

設置document的version鍵,默認鍵是_v,設為false的話就沒有這個version:

var schema = new Schema({ name: 'string' });
var Thing = mongoose.model('Thing', schema);
var thing = new Thing({ name: 'mongoose v3' });
thing.save(); // { __v: 0, name: 'mongoose v3' }
// 換 versionKey
new Schema({..}, { versionKey: '_somethingElse' })
var Thing = mongoose.model('Thing', schema);
var thing = new Thing({ name: 'mongoose v3' });
thing.save(); // { _somethingElse: 0, name: 'mongoose v3' }
//設為false
new Schema({..}, { versionKey: false });
var Thing = mongoose.model('Thing', schema);
var thing = new Thing({ name: 'no versioning please' });
thing.save(); // { name: 'no versioning please' }

Models

Models在Schema和document中作承上啟下,作用有兩個:

  • 充當MongoDB中的collection(集合)
  • 是用來構造document(文檔)的類
    所以document的創建和檢索都是來自于Models的方法。

第一個model

var schema = new mongoose.Schema({ name: 'string', size: 'string' });
var Tank = mongoose.model('Tank', schema);

構造documents

var Tank = mongoose.model('Tank', yourSchema);
var small = new Tank({ size: 'small' });
small.save(function (err) {if (err) return handleError(err);// saved!
})
// or
Tank.create({ size: 'small' }, function (err, small) {if (err) return handleError(err);// saved!
})

查詢

查詢操作有諸如find, findById, findOne, 和 where等方法,直接查API:

Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec(callback);

移除

Models有個remove方法可以用于移除指定條件的documents:

Tank.remove({ size: 'large' }, function (err) {if (err) return handleError(err);// removed!
});

更新

Models有個update方法可以用于更新指定條件的documents:

let query = { age: { $gt: 18 } };//查詢條件
let updated = { oldEnough: true };//更新結果 也可以是{ $set: { name: 'jason borne' }}
MyModel.update(query,updated ,options, fn);

Documents

如果說Models(也就為collection)相當于SQL數據庫中的表的話,那么Document就相當于行了。

更新

數據的更新操作也可以直接使用在document:

Tank.findById(id, function (err, tank) {if (err) return handleError(err);tank.size = 'large';tank.save(function (err) {if (err) return handleError(err);res.send(tank);});
});

子文檔

在構建Schema可以使用另外一個Schema作為數據類型:

var childSchema = new Schema({ name: 'string' });
var parentSchema = new Schema({children: [childSchema]
})

保存文檔的時候,子文檔在數據庫并不會獨自使用集合保存,數據庫中保存的只有父文檔的集合。不過每個子文檔都會有一個_id:

var Parent = mongoose.model('Parent', parentSchema);
var parent = new Parent({ children: [{ name: 'Matt' }, { name: 'Sarah' }] })
parent.children[0].name = 'Matthew';
parent.save(callback);//保存后數據庫中只有Parent集合var doc = parent.children.id(id);//使用`id`方法可以檢索子文檔

但是子文檔如果的生命周期有掛鉤的話也是會執行的:

childSchema.pre('save', function (next) {if ('invalid' == this.name) return next(new Error('#sadpanda'));next();
});
var parent = new Parent({ children: [{ name: 'invalid' }] });
parent.save(function (err) {console.log(err.message) // #error : sadpanda
})
添加子文檔

MongooseArray方法有想 push, unshift, addToSet等等可以添加子文檔:

var Parent = mongoose.model('Parent');
var parent = new Parent;
// create a comment
parent.children.push({ name: 'Liesl' });
var subdoc = parent.children[0];
console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }
subdoc.isNew; // true
parent.save(function (err) {if (err) return handleError(err)console.log('Success!');
});
//或者
var newdoc = parent.children.create({ name: 'Aaron' });
移除子文檔

移除子文檔可以使用remove方法:

var doc = parent.children.id(id).remove();
parent.save(function (err) {if (err) return handleError(err);console.log('the sub-doc was removed')
});
字面聲明語法

在v3版本允許直接聲明對象聲明子文檔:

var parentSchema = new Schema({children: [{ name: 'string' }]
})

查詢

所有model的查詢操作都會有兩種形式:

  • 當有回調方法作為參數時:會將查詢操作的結果傳遞給回調方法;
  • 當沒有回調方法作為參數時:會將查詢結果封裝成一個QueryBuilder接口返回。
    先看看有回調方法是怎樣的:
var Person = mongoose.model('Person', yourSchema);
// find each person with a last name matching 'Ghost', selecting the `name` and `occupation` fields
Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {if (err) return handleError(err);console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host.
})

在Mongoose中的查詢回調方法的形式都類似于:callback(error, result)。result不一定都是document的list,要看具體是什么操作。

再來看看沒有回調函數的寫法:

// find each person with a last name matching 'Ghost'
var query = Person.findOne({ 'name.last': 'Ghost' });
// selecting the `name` and `occupation` fields
query.select('name occupation');
// execute the query at a later time
query.exec(function (err, person) {if (err) return handleError(err);console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host.
})//也可以使用鏈式操作
Person
.findOne({ 'name.last': 'Ghost' })
.select('name occupation')
.exec(callback);

上面三種寫法是做同一件事情,不加回調參數時,要使用exec才會執行所有操作。

驗證

Mongoose有幾個內置的驗證器:

  • 所有的 SchemaTypes 都可以聲明required;
  • Nembers 有 min和max;
  • String有enum和match驗證。
    所有的這些都可以在 Schema創建時進行聲明。

自定義驗證

用戶還可以使用validate方法自定義驗證規則:

var toySchema = new Schema({color: String,name: String
});
var Toy = mongoose.model('Toy', toySchema);
//自定義驗證規則
Toy.schema.path('color').validate(function (value) {return /blue|green|white|red|orange|periwinkle/i.test(value);
}, 'Invalid color');
var toy = new Toy({ color: 'grease'});
toy.save(function (err) {// err is our ValidationError object// err.errors.color is a ValidatorError objectconsole.log(err.errors.color.message) // prints 'Validator "Invalid color" failed for path color with value `grease`'console.log(String(err.errors.color)) // prints 'Validator "Invalid color" failed for path color with value `grease`'console.log(err.errors.color.type)  // prints "Invalid color"console.log(err.errors.color.path)  // prints "color"console.log(err.errors.color.value) // prints "grease"console.log(err.name) // prints "ValidationError"console.log(err.message) // prints "Validation failed"
});

驗證錯誤觸發后,document會有一個errors屬性:

toy.errors.color.message === err.errors.color.message

中間件

Mongoose允許在文檔的init,validate,save和remove的前后觸發一些方法

Pre

前置有兩種形式,串行和并行。

串行
var schema = new Schema(..);
schema.pre('save', function (next) {// 中間件一個接一個next();
});
并行
var schema = new Schema(..);
schema.pre('save', true, function (next, done) {// 異步執行中間件next();doAsync(done);
});
錯誤傳遞

pre可以將傳遞錯誤:

schema.pre('save', function (next) {var err = new Error('something went wrong');next(err);
});
// later...
myDoc.save(function (err) {console.log(err.message) // something went wrong
});

Post

Post中間件是在指定操作完成后,回調函數還沒有執行前執行的方法:

parentSchema.pre("save", function(next, done) {console.log("pre save");next();console.log("after pre save");})parentSchema.post("save", function() {console.log("post save");})
...parent.save(function(err) {if (err) {console.log(err);return;}console.log("save");});
/*console
pre save
after pre save
post save
save
*/

Population

MongoDB是文檔型數據庫,所以沒有關系型數據庫joins(數據庫的兩張表通過”外鍵”,建立連接關系。) 特性。建立數據關聯時會非常麻煩,Mongoose就封裝了Population實現document中填充其他collection的document。

建立關聯

能建立關聯的字段只有ObjectId, Number, String, and Buffer四種類型可以。建立關聯只需要在聲明Schema的時候使用ref屬性就可以關聯:

var mongoose = require('mongoose'), Schema = mongoose.Schemavar personSchema = Schema({_id     : Number,name    : String,age     : Number,stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({_creator : { type: Number, ref: 'Person' },title    : String,fans     : [{ type: Number, ref: 'Person' }]
});
var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

storySchema中_creator和fans字段都關聯了Person,并且都將type設為Number。這是因為,Person和Story建立了關聯后,Story中的document的_creator或fans字段是通過Person的_id屬性關聯對應數據的,所以Story的_creator和fans要與Person的_id類型保持一致。

保存refs

要先保存被關聯的document(Person),并且將_id注冊進去:

var aaron = new Person({ _id: 0, name: 'Aaron', age: 100 });
aaron.save(function (err) {if (err) return handleError(err);var story1 = new Story({title: "Once upon a timex.",_creator: aaron._id    // 這里可以直接用aaron});story1.save(function (err) {if (err) return handleError(err);// thats it!});
})

當然了注冊的時候直接寫個0也可以,這個ref只是在檢索Person的_id字段的依據的時候。

關聯查詢

現在只需要在關聯查詢的時候使用populate聲明關聯字段就會進行關聯查詢的:

Story
.findOne({ title: 'Once upon a timex.' })
.populate('_creator')
.exec(function (err, story) {if (err) return handleError(err);console.log('The creator is %s', story._creator.name);// prints "The creator is Aaron"
})

_creator字段就會被關聯document給替換了。數組也是同樣的道理,每個元素都會被相應的document給替換。

字段篩選

可以對被關聯的document進行篩選:

Story
.findOne({ title: /timex/i })
.populate('_creator', 'name') // 只返回name字段
.exec(function (err, story) {if (err) return handleError(err);console.log('The creator is %s', story._creator.name);// prints "The creator is Aaron"console.log('The creators age is %s', story._creator.age);// prints "The creators age is null'
})

多關聯

在3.6版本后可以使用空格分割populate:

Story
.find(...)
.populate('fans author') //使用空格分開
.exec()

但是在3.6之前就只能鏈式操作:

Story
.find(...)
.populate('fans')
.populate('author')
.exec()

查詢參數

查詢的時候可以使用其他參數:

Story
.find(...)
.populate({path: 'fans',match: { age: { $gte: 21 }},select: 'name -_id',options: { limit: 5 }
})
.exec()

Plugins

Schemas允許添加插件,這樣就會想繼承一樣,每個Schemas都會有插件中定義的功能:

// lastMod.js
module.exports = exports = function lastModifiedPlugin (schema, options) {schema.add({ lastMod: Date })schema.pre('save', function (next) {this.lastMod = new Datenext()})if (options && options.index) {schema.path('lastMod').index(options.index)}
}// game-schema.js
var lastMod = require('./lastMod');
var Game = new Schema({ ... });
Game.plugin(lastMod, { index: true });// player-schema.js
var lastMod = require('./lastMod');
var Player = new Schema({ ... });
Player.plugin(lastMod);

Game和Player就都會有lastMod中定義的功能。

版權聲明:本文為CSDN博主「weixin_36743929」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_36743929/article/details/54883146

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/249141.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/249141.shtml
英文地址,請注明出處:http://en.pswp.cn/news/249141.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

前端DES加密

1、下載crypto.js文件庫 https://github.com/brix/crypto-js/releases 2、引入文件 <script type"text/javascript" src"js/jquery.min.js"></script> <script src"js/rollups/tripledes.js"></script> <script src&…

DOMBOM(source、methods、contents、Application)

何為DOM&#xff1f; Document Object Model Dom&#xff0c;是W3C組織推薦的處理可擴展標志語言的標準編程接口。在網頁上&#xff0c;組織頁面的對象被組織在一個樹形結構中&#xff0c;用來表示文檔中對象的標準模型就稱為DOM。 可以認為DOM是頁面上數據和結構的一個樹形表示…

sublime 無法下載插件解決辦法(親測有效)

最近發現sublime裝不到插件 只需要在Preferences > Package Settings > Package Control > Settings - User頁面加上以下代碼即可&#xff1a; "channels":["https://erhan.in/channel_v3.json"]上述頻道親測有效&#xff0c;如果還不能使用的小…

ES命令

基礎概念 Elasticsearch有幾個核心概念。從一開始理解這些概念會對整個學習過程有莫大的幫助。 接近實時&#xff08;NRT&#xff09; Elasticsearch是一個接近實時的搜索平臺。這意味著&#xff0c;從索引一個文檔直到這個文檔能夠被搜索到有一個輕微的延遲&#xff…

Bug : Bash on Ubuntu on Windows scp work on window but not in shell file

&#xff1a; No Permission轉載于:https://www.cnblogs.com/rgqancy/p/10726154.html

圖片做背景撐開div

需求點&#xff1a; 設計師給了一張超大背景圖&#xff0c;需要做一個不知道大小廣告位&#xff0c;要求就是要把圖片撐滿整個頁面&#xff0c;而且還得保證自適應。 解決方案一 &#xff08;親測有效&#xff09; HTML代碼&#xff1a; <div class"wrap">…

十一、jQuery的基本用法

初步接觸不是很習慣&#xff0c;之前都是用的js&#xff0c;但是jQuery去掉了js很多繁瑣的內容&#xff0c;用的不是很熟&#xff0c;所以先簡單的記錄一下&#xff0c;后續在繼續補充 jq獲取html內容: $("#id") 獲取id $(".class") class名 …

spring-注解---IOC(3)

spring--注解---IOC(3) package com.zwj.bean;public class Blue {public Blue(){System.out.println("blue...constructor");}public void init(){System.out.println("blue...init...");}public void detory(){System.out.println("blue...detory..…

絕對定位的div圖片居中自適應

需求點 固定定位div中添加圖片內容&#xff0c;保證圖片垂直居中&#xff0c;并且自適應。 一般在第三方UI組件中&#xff0c;這種布局需求較為常見 解決方案一 &#xff08;親測有效&#xff09; HTML代碼&#xff1a; <div class"el-carousel__item is-active is…

英語進階系列-A06-本周總結

本周總結 目錄Content 英語進階系列-A01-再別康橋 英語進階系列-A02-英語學習的奧秘 英語進階系列-A03-英語升級練習一 英語進階系列-A04-英語升級練習二 英語進階系列-A05-英語升級練習三 古詩Poem 再別康橋 回鄉偶書 梅花 勸學 游子吟 詞匯Vocabulary be; have; give; get; t…

在div中設置文字與內部div垂直居中

要實現如圖一所示的結果&#xff1a; html代碼如下&#xff1a; <!DOCTYPE html> <html><head lang"zh"><meta http-equiv"X-UA-Compatible" content"IEedge"><meta charset"utf-8" /><title>商…

王之泰201771010131《面向對象程序設計(java)》第九周學習總結

第一部分&#xff1a;理論知識學習部分 第7章異常、日志、斷言和調試 概念&#xff1a;異常、異常類型、異常聲明、異常拋出、 異常捕獲1.異常處理技術2.斷言的概念及使用3.基本的調試技巧 1&#xff09;異常的概念 a.Java的異常處理機制可以控制程序從錯誤產生的 位置轉移到能…

vue移動端UI框架——Vant全局引入vs局部引入

全局引入 1.在main.js中全局引入全部vant組件 優點&#xff1a;可以在所有vue文件的template中定義所需組件缺點&#xff1a;打包發布時會增加包的大小&#xff0c;Vue的SPA首屏打開時本來就有些慢&#xff0c;同時不能在js中使用類似Toast功能的組件 代碼如下&#xff1a; …

大前端完整學習路線(完整版),路線完整版

第一階段&#xff1a; HTMLCSS: HTML進階、CSS進階、divcss布局、HTMLcss整站開發、 JavaScript基礎&#xff1a; Js基礎教程、js內置對象常用方法、常見DOM樹操作大全、ECMAscript、DOM、BOM、定時器和焦點圖。 JS基本特效&#xff1a; 常見特效、例如&#xff1a;tab、…

web-8. 多框架頁面的創建

8. 多框架頁面的創建 8.1 框架概念 框架是由單個框架加上框架集構成的區域。 每個框架是指頁面中一個獨立額區&#xff0c;框架集是一個關于框架結構的頁面&#xff0c;定義本頁面的框架數、大小、布局以及框架之間的相互關系。 8.2 框架集標記 框架集文件保存了所有框架的信息…

匯編語言第二章知識梳理及思考

第二章 寄存器&#xff08;CPU工作原理&#xff09; CPU概述 CPU由運算器、控制器、寄存器等器件組成&#xff0c;這些器件靠內部總線相連。 內部總線實現CPU內部各個器件之間的聯系。 外部總線實現CPU和主板上其他器件的聯系。 寄存器概述 8086CPU有14個寄存器&#xff1a; AX…

前端面試題總結(js、html、小程序、React、ES6、Vue、算法、全棧熱門視頻資源)持續更新

Vue面試題 生命周期函數面試題 1.什么是 vue 生命周期 2.vue生命周期的作用是什么 3.第一次頁面加載會觸發哪幾個鉤子 4.簡述每個周期具體適合哪些場景 5.created和mounted的區別 6.vue獲取數據在哪個周期函數 7.請詳細說下你對vue生命周期的理解&…

Neural Networks and Deep Learning 讀書筆記

1 轉載于:https://www.cnblogs.com/jellyj/p/9867103.html

JS中的數據類型轉換:String轉換成Number的3種方法

今天有個學員問了個關于數據類型轉換的問題&#xff0c;我覺得這個是可以給大家說一下的。 JavaScript中&#xff0c;可以通過以下3種方法來將string值轉換成number&#xff1a; 1.調用Number()來對string進行值類型轉換。 2.parseInt()。 3.parseFloat()。 Number() 使用…

Java學習——使用Static修飾符

程序功能&#xff1a;通過兩個類 StaticDemo、LX4_1 說明靜態變量/方法與實例變量/方法的區別。 package Pack1;public class Try {public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println("靜態變量x"StaticDemo.getX());非…