替换空格和格式字符串

时间:2017-01-18 09:39:06

标签: javascript node.js mongodb mongoose aggregation-framework

我找不到如何用MongoDB替换whiteSpace请求中的aggregate以及如何删除字符串的一部分。(我可能需要使用正则表达式)。< / p>

我的文档示例:

{
    "_id": "57dfa5c9xxd76b65426d5cca",
    "battle_id": "5744f01d1ad716a349c4999a",
    "is_first": false,
    "title": "division 1 #3"
},    
{
    "_id": "13dfa529dxd123x5426d5ccb",
    "battle_id": "1244x51d1aq546a349c423rcc",
    "is_first": true,
    "title": "division gold #5"
}

我目前在做什么:

.project({
    "battle_id": "$battle_id",  
    "is_first": {
        $cond: [
            { $eq : ["$rank" , 1] }, 
            true, 
            false
        ]
    }, 
    "title": { $toLower: "$battle.title" }
})

是否可以按"_"个字符更改每个空白区域,或者在请求后我是否需要在forEach()中执行此操作?

此外,是否可以格式化字符串以永远不会返回#3例如?

我需要的结果(更改在标题中):

{
    "_id": "57dfa5c9xxd76b65426d5cca",
    "battle_id": "5744f01d1ad716a349c4999a",
    "is_first": false,
    "title": "division_1"
},    
{
    "_id": "13dfa529dxd123x5426d5ccb",
    "battle_id": "1244x51d1aq546a349c423rcc",
    "is_first": true,
    "title": "division_gold"
}

1 个答案:

答案 0 :(得分:0)

您可以使用Regular ExpressionsArray#map()替换空格和格式字符串以获取result

&#13;
&#13;
var arr = [{"_id": "57dfa5c9xxd76b65426d5cca","battle_id": "5744f01d1ad716a349c4999a","is_first": false,"title": "division 1 #3"},{"_id": "13dfa529dxd123x5426d5ccb","battle_id": "1244x51d1aq546a349c423rcc","is_first": true,"title": "division gold #5"}],
    result = arr.map(i => {
      return {
        '_id': i._id,
        'battle_id': i.battle_id,
        'is_first': i.is_first,
        'title': i.title.replace(/\s#[0-9]+/g, '').replace(/\s/,'_')
      };
    });

console.log(result);
&#13;
&#13;
&#13;