Nodejs 中mongoose的作用是什么,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

成都創新互聯公司主營蒙山網站建設的網絡公司,主營網站建設方案,重慶APP開發,蒙山h5微信小程序開發搭建,蒙山網站營銷推廣歡迎蒙山等地區企業咨詢
Schema
開始我們就要講到Schema,一個Schema對應的是MongoDB的collection(相當于SQL table),并且定義其結構。
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可用Type:
.String (ex: 'ABCD')
.Number (ex: 123)
.Date (ex: new Date)
.Buffer (ex: new Buffer(0))
.Boolean (ex: false)
.Schema.Types.Mixed (ex: {any:{thing:'ok'}})
.Schema.Types.ObjectId (ex:new mongoose.Types.ObjectID)
.Array (ex:[1,2,3])
.Schema.Types.Decimal128
.Map (ex: new Map([['key','value']]))
我們可以通過一段代碼,將Schema轉化成Model: mongoose.model(modelName,Schema)
var Blog = mongoose.model('Blog', blogSchema);賦予Schema方法,當方法轉成Model的時候,會將方法給予Model
//創建一個變量,Schema
var animalSchema = new Schema({ name: String, type: String });
//將方法賦予這個Schema
animalSchema.methods.findSimilarTypes = function(cb) {
return this.model('Animal').find({ type: this.type }, cb);
};
var Animal = mongoose.model('Animal', animalSchema);
var dog = new Animal({ type: 'dog' });
dog.findSimilarTypes(function(err, dogs) {
console.log(dogs); // woof
});在Schema方法里,不要使用箭頭函數,它會重新綁定this。
賦予Schema static (靜態)方法,我們繼續使用上面的例子:
//賦予靜態方法,可以再Model不實例化的情況下調用
animalSchema.statics.findByName = function(name, cb) {
return this.find({ name: new RegExp(name, 'i') }, cb);
};
var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function(err, animals) {
console.log(animals);
});Schema索引 index
MongoDB支持二級索引,在mongoose,我們可以將索引定在Schema層。
var animalSchema = new Schema({
name: String,
type: String,
tags: { type: [String], index: true } // 聲明在字段層
});
animalSchema.index({ name: 1, type: -1 }); // 聲明在使用index(二級索引)的時候記得要disable Mongodb 的 autoIndex。
mongoose.connect('mongodb://user:pass@localhost:port/database', { autoIndex: false });
// 或者
mongoose.createConnection('mongodb://user:pass@localhost:port/database', { autoIndex: false });
// 或者
animalSchema.set('autoIndex', false);
// 或者
new Schema({..}, { autoIndex: false });虛擬化
// 聲明一個Schema
var personSchema = new Schema({
name: {
first: String,
last: String
}
});
// 轉成Model
var Person = mongoose.model('Person', personSchema);
// 實例化Model
var axl = new Person({
name: { first: 'Axl', last: 'Rose' }
});
//1.如果我們想要打印Person的姓名
console.log(axl.name.first + ' ' + axl.name.last); // Axl Rose
//2.使用虛擬化,我們聲明一個虛擬字段,然后通過get給其賦值
personSchema.virtual('fullName').get(function () {
return this.name.first + ' ' + this.name.last;
});
console.log(axl.fullName); // Axl Rose別名
var personSchema = new Schema({
n: {
type: String,
// 給予 n 別名 name,n與name指向同一個值
alias: 'name'
}
});
// 修改name同樣修改n,方向一樣
var person = new Person({ name: 'Val' });
console.log(person); // { n: 'Val' }
console.log(person.toObject({ virtuals: true })); // { n: 'Val', name: 'Val' }
console.log(person.name); // "Val"
person.name = 'Not Val';
console.log(person); // { n: 'Not Val' }
Model & Documents增
var Tank = mongoose.model('Tank', yourSchema);
var small = new Tank({ size: 'small' });
//使用save的方法
small.save(function (err) {
if (err) return handleError(err);
// saved!
});
// 或者 使用create
Tank.create({ size: 'small' }, function (err, small) {
if (err) return handleError(err);
// saved!
});
// 或者 使用insertMany/insertOne
Tank.insertMany([{ size: 'small' }], function(err) {
});刪
//deleteOne 或者 deleteMany
Tank.deleteOne({ size: 'large' }, function (err) {
if (err) return handleError(err);
// 只刪掉符合項的第一條
});改
Tank.updateOne({ size: 'large' }, { name: 'T-90' }, function(err, res) {
});
// findOneAndUpdate 查找出相應的數據,修改,并返還給程序查
// 查提供了多種方式,find,findById,findOne,和where
Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec(callback);關于Nodejs 中mongoose的作用是什么問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創新互聯行業資訊頻道了解更多相關知識。
當前題目:Nodejs中mongoose的作用是什么
瀏覽路徑:http://www.yijiale78.com/article36/pehgpg.html
成都網站建設公司_創新互聯,為您提供微信小程序、網站維護、Google、App開發、云服務器、
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯