簡體   English   中英

貓鼬查詢與結果和結果我發現結果的字段名稱

[英]Mongoose query with find and as a result the field name where i found results

由於查詢的原因,我試圖將字段找到正則表達式,例如:

如果我在facebook字段中找到結果;

假設我的req.body.key ='crazy',在我的數據庫中,我在facebook字段中擁有'crazy'。 由於查詢我的CitizenProfile模型,我想要更多我找到結果的字段。 在這種情況下,字段名稱為“ facebook”

Obs:這個查詢已經給了模型,我只需要找到與正則表達式匹配的字段名稱即可。 能做到嗎? 謝謝!

    app.post('/v1/profile/search', (req, res) => {
    async.waterfall([
        function (next) {
            CitizenProfile.find({
                $or: [{'first_name': {$regex: req.body.key, $options:'i'}}, {'middle_name': {$regex: req.body.key, $options:'i'}},
                    {'last_name': {$regex: req.body.key, $options:'i'}}, {'email': {$regex: req.body.key, $options:'i'}},
                    {'facebook': {$regex: req.body.key, $options:'i'}}, {'linkedin': {$regex: req.body.key, $options:'i'}},
                    {'skills': {$regex: req.body.key, $options:'i'}}],
                'id_citizen': {$ne: req.body.id_citizen},
                'is_hidden': {$ne: true}
            })
                .exec(function (err, data) {
                   ...

我不認為MongoDB具有這種功能(如果我錯了,請改正任何人)。

由於您只取回與正則表達式匹配的文檔,因此必須將正則表達式再次應用於這些相同的文檔以查找字段。

未經測試,但我認為您會做類似的事情

let regex = new RegExp(req.body.key, 'i');

CitizenProfile.find({
    $or: [
        { 'first_name': regex }, 
        { 'middle_name': regex },
        { 'last_name': regex }, 
        { 'email': regex },
        { 'facebook': regex }, 
        { 'linkedin': regex },
        { 'skills': regex }
    ],
    'id_citizen': { $ne: req.body.id_citizen },
    'is_hidden': { $ne: true }
}).exec(function (err, profiles) => {   
    // loop through found documents
    profiles.forEach(function (profile) {
        profile = profile.toJSON();
        // filter fields based on regular expression
        let keys = Object.keys(profile).filter(k => regex.test(profile[k]));
        // do something with keys
        console.log(keys);
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM