Mongoose 将 createdAt 保存为 Double 而不是 Date

Mongoose saves createdAt as Double not Date

我希望 mongoose 将 createdAt 字段保存为 Date 对象而不是 Double。请帮忙

这是我的架构

const allSchema = new mongoose.Schema({ any: {} }, {
    safe: false,
    strict: false,
    versionKey: false,
    bufferCommands: false,
    validateBeforeSave: false,
    timestamps: { createdAt: 'createdAt', updatedAt: 'updated_at' },
});

这就是我使用它的方式。我正在使用 javascript 日期对象设置 createdAt。但是它被保存为Double。我需要将其保存为日期,以便能够在这些文档上使用 TTL 索引,使它们在 X 秒后过期。

const con = mongoose.createConnection(uri, opts);
const model = con.model('allSchema', allSchema, collectionName, true);
model.then(async (m) => {

        // here
        fields.createdAt = Date.now();

        // check if we have fields as objects need to be stringify before insert
         Object.keys(fields).forEach((key) => {
            const val = fields[key] || '';
             if (typeof val === 'object') {
                 fields[key] = JSON.stringify(val).toString();
             }
         });
        return m.collection.insertOne(fields);
    });

提前致谢

而是在时间戳中使用 created_atupdated_at

toJSON: { virtuals: true }, timestamps: true

这将自动添加 created_atupdated_at 字段。

Date.now() - returns 一个数字。如果您需要像 BSON Date 对象一样存储日期,请改用 new Date(Date.now())