【问题标题】:Some "ObjectId" is not getting replaced一些“ObjectId”没有被替换
【发布时间】:2019-01-02 17:36:25
【问题描述】:

我正在转换 mongodb 的文档_id
from :"_id" : ObjectId("5c09b6002351d50e100c5f6c"),
To:"_id" : "5c09b6002351d50e100c5f6c",

我正在使用正则表达式text.replace(/ObjectId\((.*)\)/gi,"$1");

问题是一些 ObjectId 被转换,但有些没有被转换,不知道为什么..

small example code of what i am doing:

var fs=require('fs');
var data = fs.readFileSync('./abc.json');      
str = data.toString()
str = str.replace(/ObjectId\((.*)\)/g,"$1");
fs.writeFile('str','data.json');

note:我已经使用 Studio 3T 导出了输入文件

提前致谢!

【问题讨论】:

  • 你有问题,然后你使用了正则表达式,现在你有两个问题。
  • 你的意思是输入文件本身有问题? @cgTag
  • 不,这是一句老话 :) blog.codinghorror.com/…

标签: javascript node.js regex mongodb


【解决方案1】:

问题是你的.* 也匹配了一些完整的“ObjectId(...)”表达式。

解决方案是使用非贪婪组:

text.replace(/ObjectId\((.*?)\)/gi,"$1");

如果可以的话,一个更好(性能更高)的方法是明确说明:

text.replace(/ObjectId\(("[^"]*")\)/gi,"$1");

【讨论】:

  • @PrabhatMishra 你能建立a MCVE吗?
  • @PrabhatMishra 是的,但仍然无法检查或重现您的问题。
  • 我已经使用 Studio 3T 导出了这个文件,你可以尝试重现问题..@Denys
猜你喜欢
  • 2014-08-15
  • 2020-12-11
  • 2013-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-14
  • 1970-01-01
相关资源
最近更新 更多