溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Mongoose中怎么實(shí)現(xiàn)虛擬字段查詢

發(fā)布時間:2021-07-20 15:51:27 來源:億速云 閱讀:147 作者:Leah 欄目:web開發(fā)

今天就跟大家聊聊有關(guān)Mongoose中怎么實(shí)現(xiàn)虛擬字段查詢,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

Mongoose 中的 Hook

Mongoose Schema幾乎所有靜態(tài)方法和對象方法都添加了 .pre和.post鉤子。 這些鉤子其實(shí)就是函數(shù)鉤子,采用hooks-js的實(shí)現(xiàn)。

來自官網(wǎng)的例子:

var hooks = require('hooks')
 , Document = require('./path/to/some/document/constructor');
// Add hooks' methods: `hook`, `pre`, and `post`
for (var k in hooks) {
 Document[k] = hooks[k];
}
// Define a new method that is able to invoke pre and post middleware
Document.hook('save', Document.prototype.save);

// 上述代碼在mongoose中實(shí)現(xiàn)
/////////////////////////////////////////////////////////////////////
// 下面的代碼則是mongoose提供的Hook API

// Define a middleware function to be invoked before 'save'
Document.pre('save', function validate(next) {
 // ...
});

Document.save()被調(diào)用時,上述validate函數(shù)就會被回調(diào)。

添加查詢鉤子

Mongoose沒有對hooks-js進(jìn)一步封裝,這意味著我們不能對所有Query方法設(shè)置鉤子, 只能一一枚舉需要監(jiān)視的方法。當(dāng)然,這不影響我們進(jìn)行代碼復(fù)用。

// 設(shè)置 findOne 和 find 鉤子
CompanySchema.pre('findOne', preFind).pre('find', preFind);

接下來便著手實(shí)現(xiàn)preFind函數(shù)。

實(shí)現(xiàn)虛擬查詢

在鉤子(preFind)中,我們可以更改查詢條件借此實(shí)現(xiàn)虛擬查詢。 值得注意的是,完全可控的Query意味著我們可以實(shí)現(xiàn)任何形式的虛擬查詢。

 例如全文檢索:

function preFind() {
 var word = this.getQuery().word;
 if(word === undefined) return;

 // 從真實(shí)的Query中刪掉虛擬屬性
 delete this._conditions.word;
 // 構(gòu)造正則表達(dá)式
 var regex = new RegExp(word);
 // 全文檢索
 this.where({ $or: [{ title: regex }, { content: regex }, { author: regex }] });
}

看完上述內(nèi)容,你們對Mongoose中怎么實(shí)現(xiàn)虛擬字段查詢有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI