mongoosJS更新嵌套日期值

时间:2022-09-10 19:14:34

I'm not getting an updated value when trying to set a date

在尝试设置日期时,我没有获得更新的值

The Schema looks like this

Schema看起来像这样

const CouponSchema = new Schema({
    coupon: {
        type: String
        ,required: true
    }
    ,type: {
        type: String
        ,required: true
    }
    ,user_id: {
        type: mongoose.Schema.ObjectId
        ,required: true
    }
    ,date: {
        issued: {
            type: Date
            ,default: Date.now
        }
        ,redeemed: {
            type: Date
            ,default: null
        }
    }
});

I've tried this

我试过这个

module.exports.redeem = function( id, callback ) {
    Coupon.findByIdAndUpdate( id, {
        $set: {
            "date.redeemed": Date.now
        }
    }, callback);
}

And this

和这个

module.exports.redeem = function( id, callback ) {
    Coupon.findByIdAndUpdate( id, {
        $set: {
            "date": {
                "redeemed": Date.now
            }
        }
    }, callback);
}

I get no errors, but the dates never get populated. Suggestions?

我没有错误,但日期永远不会填充。建议?

1 个解决方案

#1


0  

so, You are using Date.now() that returns numbered value timestamp like below:

所以,你正在使用Date.now()返回编号值时间戳,如下所示:

> Date.now()
1517473075986

and you are passing this to a Date type field, that only takes Date Objects, following command returns Date Object. which can be accepted by Date type fields.

并且您将此传递给日期类型字段,该字段仅接受日期对象,以下命令返回日期对象。可以通过日期类型字段接受。

> new Date()
2018-02-01T08:19:49.360Z

example:

例:

{
  issued: {
    type: Date,
    default: new Date()
  },
  redeemed: {
    type: Date,
    default: new Date()
  }
}

So, insted of Date.now() you can pass new Date() , that should work. ;)

因此,在Date.now()中,您可以传递新的Date(),这应该有效。 ;)

#1


0  

so, You are using Date.now() that returns numbered value timestamp like below:

所以,你正在使用Date.now()返回编号值时间戳,如下所示:

> Date.now()
1517473075986

and you are passing this to a Date type field, that only takes Date Objects, following command returns Date Object. which can be accepted by Date type fields.

并且您将此传递给日期类型字段,该字段仅接受日期对象,以下命令返回日期对象。可以通过日期类型字段接受。

> new Date()
2018-02-01T08:19:49.360Z

example:

例:

{
  issued: {
    type: Date,
    default: new Date()
  },
  redeemed: {
    type: Date,
    default: new Date()
  }
}

So, insted of Date.now() you can pass new Date() , that should work. ;)

因此,在Date.now()中,您可以传递新的Date(),这应该有效。 ;)