[英]MongoDB Javascript replace() fails with "TypeError: Cannot call method 'replace' of undefined"
I have a collection that contains customer contact data but some fields need to be cleaned up and special characters removed.我有一个包含客户联系数据的集合,但需要清理某些字段并删除特殊字符。
This is the script I wrote ( list of fields has been edited for brevity )这是我写的脚本(为简洁起见,编辑了字段列表)
// 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 + "\""
);
}
When I run it from the command line当我从命令行运行它时
mongo localhost:27000/queue_xyz get_contacts_cleanup.js > contacts.csv
I get this error in the CSV file我在 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
Why it is unloading the first 2 rows but fails after that.为什么它卸载前 2 行但之后失败。 What am I missing here?我在这里缺少什么?
The "crash" is due to the fact that document in my collection that has no "Note" value so running Note.replace
when Note isn't a string will not work. “崩溃”是由于我的集合中的文档没有“Note”值,因此当 Note 不是字符串时运行Note.replace
将不起作用。 I re-wrote the cursor iteration piece like so我像这样重写了游标迭代部分
...while (cursor.hasNext()) {
var record = cursor.next();
var Note = record.Note ? record.Note.replace(/[\n\r]+/g, '') : '';
print(
"\"" + record._id + "\"|" +
...
"\"" + record.Note + "\"|" +
...
I downloaded 10k documents without error and I am going through data validation.我下载了 10k 个文件,没有错误,我正在接受数据验证。 So far, so good.到现在为止还挺好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.