【问题标题】:How to manually set createdAt timestamp in mongoDB using mongoose?如何使用 mongoose 在 mongoDB 中手动设置 createdAt 时间戳?
【发布时间】:2019-06-24 04:51:51
【问题描述】:

我正在尝试通过将时间戳添加到之前缺少时间戳的所有行来迁移我的数据库。我已经使用 _id 计算了 createdAt 时间戳,但我无法设置时间戳。我在这里做错了什么? 有人可以帮忙吗?

    let Question = db.model('Question');

    let items = await Question.findWithDeleted();

    let processedIds = items.map((q) => q._id);
    processedIds.forEach(function (id) {

        const timestamp = id.getTimestamp();

        // const date = new Date(parseInt(timestamp, 16) * 1000);
        // echo(timestamp)
        Question.update({ "_id": id }, { "$set": { createdAt: timestamp } }, (h) => {
            console.log(h);
        });

    });

这是模型:

const Question = new Schema({ “类型”: { 类型:字符串, 修剪:真的, 枚举:Object.values(问题类型), required: '问题类型是必需的' }, “文本”: { 类型:字符串, 要求:真 }, "desc": NotRequiredStringSchema, “选项”: [{ “id”:对象 ID, “名称”:NotRequiredStringSchema, “helperText”:NotRequiredStringSchema, “icon_key”:NotRequiredStringSchema, “icon_url”:NotRequiredStringSchema, “icon_svg”:NotRequiredStringSchema }], “placeHolder”:NotRequiredStringSchema, “buttonPosition”:NotRequiredStringSchema, “buttonText”:NotRequiredStringSchema, "buttonHoverText": NotRequiredStringSchema, “helperText”:NotRequiredStringSchema, “最大”:数字, “分钟”:数字, “默认”:混合, “icon_key”:NotRequiredStringSchema, “icon_url”:NotRequiredStringSchema, “icon_svg”:NotRequiredStringSchema, "showTick": { type: Boolean, required: false, default: false }, “朗”:{ 要求:真, 类型:地图, 的: { 类型:地图, 的:字符串 } } }, { 时间戳:真 });

【问题讨论】:

  • 你能发布架构吗
  • 您现在可以查看@KalanaDemel 吗?
  • 您要在现有记录上添加时间戳还是在新创建或更新的记录上添加时间戳。
  • @Abhinav Jain,检查解决方案是否有帮助

标签: node.js mongodb mongoose


【解决方案1】:

问题是您的架构不包含 createdAt 字段,猫鼬默认情况下会在启用严格选项的情况下保存数据,如果您的架构不包含字段,则无法向其添加新字段@ 987654321@。因此,您首先需要将 createdAt 字段添加到您的架构中,以下只是一个示例。

 createdAt: {type: Date, default: Date.now}

将其添加为字段后,您的查询应该可以正常工作。

【讨论】:

  • 我有时间戳:是的,所以它有这些字段,对吗?并且解决方案不起作用
  • 哦,没看到标志,但它对你有用:D
【解决方案2】:

如果你让你的架构像这样

const SchemaName = new Schema({
 .......
}, {
  timestamps: true
})

它会自动创建 createdAt 和 updatedAt 字段,并在每次执行创建和更新操作时更新它们的值。

现在其他情况,如果您手动创建类似于此架构的 createdAt 和 updatedAt 字段

const SchemaName = new Schema({
 .......
 createdAt: { type: Date, default: Date.now },
 updatedAt: { type: Date, default: Date.now }
})

然后您可以使用middleware 更新 createdAt 和 updatedAt 值来创建和更新记录。

SchemaName.post('save', (doc) => {
  console.log('%s has been saved', doc._id);
});

SchemaName.pre('update', () => {
  this.update({},{ $set: { updatedAt: new Date() } });
});

【讨论】:

    猜你喜欢
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    相关资源
    最近更新 更多