将JSON插入MongoDB中,自动转换字符串中的日期

Inserting JSON into MongoDB converting dates from strings automatically

本文关键字:转换 字符串 日期 JSON 插入 MongoDB      更新时间:2023-09-26

我有一些对象使用键updated_atcreated_at,它们具有类似2012-08-29T16:04:34-04:00的字符串时间戳。我正在将其插入MongoDB中。问题是,每个对象都可以有数量可变的updated_atcreated_at实例(它们在中的数组中)。有没有任何代码可以用来在数组中搜索updated_atcreated_at,并用$.created_at = new Date($.created_at)替换这些值?

{
    "name":"thomas",
    "created_at":"2012-08-29T16:04:34-04:00",
    "updated_at":"2012-08-29T16:04:34-04:00",
    "logs":[
        {
            "something":"something",
            "created_at":"2012-08-29T16:04:34-04:00",
        },
        {
            "something":"something",
            "created_at":"2012-08-29T16:04:34-04:00",
        },
    ]
}

{
    "name":"thomas",
    "created_at":new Date("2012-08-29T16:04:34-04:00"),
    "updated_at":new Date("2012-08-29T16:04:34-04:00"),
    "logs":[
        {
            "something":"something",
            "created_at":new Date("2012-08-29T16:04:34-04:00"),
        },
        {
            "something":"something",
            "created_at":new Date("2012-08-29T16:04:34-04:00"),
        },
    ]
}
// store your data object in x
x = {
    "name":"thomas",
    "created_at":"2012-08-29T16:04:34-04:00",
    "updated_at":"2012-08-29T16:04:34-04:00",
    "logs":[
        {
            "something":"something",
            "created_at":"2012-08-29T16:04:34-04:00",
        },
        {
            "something":"something",
            "created_at":"2012-08-29T16:04:34-04:00",
        },
    ]
}
// create a traversal function to recurse
function traverse(o) {
    // loop through object
    for (i in o) {
        // if it is a matched key (current regex matches created_at or updated_at)
        // parse the item as a date, and re-store object
        if(i.match(/(cre|upd)ated_at/)){
            o[i] = new Date(o[i])
        }
        // if the key we are looking at is an object, then recurse!
        if (typeof(o[i])=="object") {
            traverse(o[i])
        }
    }
}
// fire it up!
traverse(x)
// check the results
console.dir(x)
// store your data object in x
x = {
    "name":"thomas",
    "created_at":"2012-08-29T16:04:34-04:00",
    "updated_at":"2012-08-29T16:04:34-04:00",
    "logs":[
        {
            "something":"something",
            "created_at":"2012-08-29T16:04:34-04:00",
        },
        {
            "something":"something",
            "created_at":"2012-08-29T16:04:34-04:00",
        },
    ]
}
// loop through each element of the logs array
for(y in x.logs){
    // modify the `created_at` value of the y-th element
    // by wrapping with the desired string
    x.logs[y].created_at = "new Date(" + x.logs[y].created_at + ")"
}
// check the final format of the object
console.dir(x)

注意事项:

该对象存储一个包含new Date ... ammendment的字符串-要存储操作的结果,您需要将修改行调整为…

x.logs[y].created_at = new Date( x.logs[y].created_at )