快速上手
請(qǐng)先安裝 MongoDB 和 Node.js信夫。
下一步,npm
安裝Mongoose:
$ npm install mongoose
假設(shè)我們都很喜歡喵星人准潭,想在MongoDB里記錄每只我們見過的喵星人。 首先我們要在項(xiàng)目中引入 mongoose 域仇,然后連接我們本地的 test
數(shù)據(jù)庫刑然。
// getting-started.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
connect()
返回一個(gè)狀態(tài)待定(pending)的連接, 接著我們加上成功提醒和失敗警告暇务。
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
});
連接成功時(shí)泼掠,回調(diào)函數(shù)會(huì)被調(diào)用。簡潔起見般卑, 我們假設(shè)下面所有函數(shù)都運(yùn)行在這個(gè)回調(diào)函數(shù)里武鲁。
Mongoose 里,一切都始于Schema蝠检。 現(xiàn)在我們來看一個(gè)例子:
var kittySchema = mongoose.Schema({
name: String
});
很好沐鼠,我們得到了一個(gè)帶有 String
類型 name
屬性的 schema 。 接著我們需要把這個(gè) schema 編譯成一個(gè) Model:
var Kitten = mongoose.model('Kitten', kittySchema);
model 是我們構(gòu)造 document 的 Class。 在例子中饲梭,每個(gè) document 都是一只喵乘盖,它的屬性和行為都會(huì)被聲明在 schema。 現(xiàn)在我們來“創(chuàng)造”一只貓:
var felyne = new Kitten({ name: 'Felyne' });
console.log(felyne.name); // 'Felyne'
不會(huì)喵怎么算喵星人憔涉,現(xiàn)在給喵星人 document 加個(gè) "speak" 方法:
// 譯者注:注意了订框, method 是給 document 用的
// NOTE: methods must be added to the schema before compiling it with mongoose.model()
kittySchema.methods.speak = function () {
var greeting = this.name
? "Meow name is " + this.name
: "I don't have a name";
console.log(greeting);
}
var Kitten = mongoose.model('Kitten', kittySchema);
加在 schema methods
屬性的函數(shù)會(huì)編譯到 Model
的 prototype, 也會(huì)暴露到每個(gè) document 實(shí)例:
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.speak(); // "Meow name is fluffy"
贊兜叨!是一只會(huì)說話的瞄星人穿扳!emmmmm雖然我們還沒吧它存到數(shù)據(jù)庫里。 每個(gè) document 會(huì)在調(diào)用他的 save 方法后保存到數(shù)據(jù)庫国旷。 注意回調(diào)函數(shù)的第一個(gè)參數(shù)永遠(yuǎn)是 error 矛物。
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
fluffy.speak();
});
后來我們收集了好多喵,就可以通過以下方法獲取喵星人 model 里的所有數(shù)據(jù):
Kitten.find(function (err, kittens) {
if (err) return console.error(err);
console.log(kittens);
})
如果我們想獲取特定的數(shù)據(jù)跪但, 可以了解一下 query履羞。
// 這么寫可以獲取所有 name 為 "Fluff" 開頭的數(shù)據(jù)
Kitten.find({ name: /^fluff/ }, callback);
可喜可賀
我們已經(jīng)看完快速上手啦!上面我們寫了一個(gè) schema 屡久,添加了 method 忆首,然后用 Mongoose 把我們的貓儲(chǔ)存到了數(shù)據(jù)庫, 接著我們可以到指引 和 API 文檔了解更多信息被环。
文檔鏈接: https://mongoosedoc.top/docs/index.html
GitHub倉庫: https://github.com/ssshooter/mongoose-doc-cn
歡迎加入