将JSON插入MongoDB会自动从字符串中转换日期

时间:2012-08-29 20:29:52

标签: javascript json mongodb object

我的对象使用密钥updated_atcreated_at,其字符串时间戳如2012-08-29T16:04:34-04:00。我将其插入MongoDB。 catch是每个对象可以有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"),
        },
    ]
}

2 个答案:

答案 0 :(得分:1)

// 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)

答案 1 :(得分:0)

// 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 ...修正的字符串 - 为了存储操作的结果,您需要将修改行调整为...

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