簡體   English   中英

MongoDB Javascript replace() 失敗並顯示“TypeError:無法調用未定義的方法‘replace’”

[英]MongoDB Javascript replace() fails with "TypeError: Cannot call method 'replace' of undefined"

我有一個包含客戶聯系數據的集合,但需要清理某些字段並刪除特殊字符。

這是我寫的腳本(為簡潔起見,編輯了字段列表

// VARs to calculate date difference - I am sure there is a better way
var v_curr_timestamp = new Date();
var v_curr_day = v_curr_timestamp.getDate();
var v_curr_month = v_curr_timestamp.getMonth();
var v_curr_year = v_curr_timestamp.getFullYear();
var v_stop_date = new Date(v_curr_year, v_curr_month, v_curr_day, 0, 0, 0, 0);
v_diff_days = 1;
var v_start_date = new Date(v_curr_year, v_curr_month, v_curr_day - v_diff_days, 0, 0, 0, 0);

// CSV file header row
print("\"_id\"|\"UserID\"...|\"GroupIDs\"");

// Create cursor
var cursor = db.contacts.find({
  $and: [{
      UpdatedAt: {
        $gte: Date.parse(v_start_date) / 1000
      }
    },

    {
      UpdatedAt: {
        $lt: Date.parse(v_stop_date) / 1000
      }
    }
  ]
}).limit(100); // limit the number of returned documents - testing only

while (cursor.hasNext()) {
    var record = cursor.next();
    var NoteClean = record.Note.replace(/\n/g, '');
  print(
    "\"" + record._id + "\"|" +
    "\"" + record.UserID + "\"|" +
...
    "\"" + NoteClean + "\"|" +
...
    "\"" + record.GroupIDs + "\""
  );
}

當我從命令行運行它時

mongo localhost:27000/queue_xyz get_contacts_cleanup.js > contacts.csv

我在 CSV 文件中收到此錯誤

"_id"|"UserID"|"PhoneNumber"|"Source"|"PrivateLabelID"|"OptOut"|"Blocked"|"Deleted"|"Note"|"CreatedAt"|"UpdatedAt"|"FirstName"|"LastName"|"Email"|"Custom1"|"Custom2"|"Custom3"|"Custom4"|"Custom5"|"GroupIDs"
"5e4f63cf404dfb30c51b0403"|"568665"|"3379628807"|"1"|"1"|"undefined"|"undefined"|"undefined"|""|"1582261199"|"1582261199"|"Colby"|"Mczeal"|""|"undefined"|"undefined"|"undefined"|"undefined"|"undefined"|"[object Object]"
2020-02-21T11:43:07.323-0500 E QUERY    TypeError: Cannot call method 'replace' of undefined
    at get_contacts_cleanup.js:31:30 at get_contacts_cleanup.js:31
failed to load: get_contacts_cleanup.js

為什么它卸載前 2 行但之后失敗。 我在這里缺少什么?

“崩潰”是由於我的集合中的文檔沒有“Note”值,因此當 Note 不是字符串時運行Note.replace將不起作用。 我像這樣重寫了游標迭代部分

...while (cursor.hasNext()) {
        var record = cursor.next();
        var Note = record.Note ? record.Note.replace(/[\n\r]+/g, '') : '';
  print(
    "\"" + record._id + "\"|" +
...
    "\"" + record.Note + "\"|" +
...

我下載了 10k 個文件,沒有錯誤,我正在接受數據驗證。 到現在為止還挺好。

暫無
暫無

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

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