【问题标题】:unable to update the createdAt property in mongoose?无法更新 mongoose 中的 createdAt 属性?
【发布时间】:2021-02-06 07:22:50
【问题描述】:

各位专家您好,

可能问题似乎重复,但我的业务案例略有不同,请多多包涵。

我正在使用其他开发人员定义的旧架构,其中缺少 createdAt 和 updatedAt 属性。所以我通过添加{ timestamps: true } 更新了架构。每当我创建新文档时都没有问题。它按预期工作,但现有/旧文档在那里,所以我试图通过编写单独的脚本并从_id 属性(如_id.getTimestamp())读取创建时间来添加createdAt 属性。我能够从 _id 中提取创建时间,但无法在现有文档中添加 createdAt 属性。旧文档/数据非常重要,但企业希望将createdAt 属性添加到旧文档中。

我正在使用 mongoose NPM 库,版本是:"mongoose": "^5.9.16",

架构示例如下:

    const mongoose = require("mongoose");
    const Schema = mongoose.Schema;
    
    const profileSchema = new Schema(
      {
        name: {
          type: String,
          required: true
        },
        profile_number: {
          type: Number
        },
        view: {
          type: String
        },
     
      },
      { timestamps: true }
    );
module.exports = mongoose.model("profile", profileSchema, "profile");

添加 createdAt 属性并从 _id

中提取时间戳的脚本
    const mongoose = require("mongoose");
    const Profile= require("../../models/Profile/ProfileModel");
    
    /****
     * * Fetch all Portfolios List
     * */
    exports.getAllProfileList = async (req, res, next) => {
      try {
    
        const profileResult = await Profile.find({},{_id:1}).exec(); //return all ids
        const timeStampExtract = await profileResult.map(item => {
          console.log("Item is:", item._id.getTimestamp());
// trying to update createdAt time by extacting item._id.getTimestamp()
          Profile.findOneAndUpdate(
            { _id: item._id },
            { $set: { createdAt: item._id.getTimestamp() } },
            { upsert: true }
          )
            .then(res => console.log("Response:"))
            .catch(error => console.log("Error is:", error.message));
          return item._id.getTimestamp();
        });
   
        if (!profileResult ) {
          return res
            .status(400)
            .json({ message: "Unable to find profile list", statusCode: 400 });
        }
        res
          .status(200)
          .json({ totalCount: profileResult.length, data: timeStampExtract });
      } catch (error) {
        logger.error(error.message);
        return res.status(500).json({ message: error.message, statusCode: 500 });
      }
    };

默认情况下 createdAt 是不可变的?

有人可以帮忙吗?这将是很大的帮助。

感谢所有专家

【问题讨论】:

  • 当我们在架构中使用 { timestamps: true } 时,它会将 createdAt 和 updatedAt 属性添加到文档中。我猜,createdAt 是不可变的,因为它不允许更新值。如果我们将在 createdAt 名称之外添加其他键,例如 created_At 它正在工作

标签: node.js mongodb express mongoose data-migration


【解决方案1】:

由于某些文档是在 timestamps 选项设置为 false(这是默认值)时创建的,因此 mongoose 不会知道这些时间戳。因此,item._id.getTimestamp() 将返回 undefined。

您可以做的是重新创建 createdAt 不存在的条目。如果启用该选项,Mongoose 将自动生成时间戳并将其设置为当前时间戳:

    const profilesWithoutCreated = await Profile.find({createdAt: {$exists: false}}).exec();
    const timeStampExtract = [];
    let newProfile;
    for (const profile of profiles) {
       newProfile = new Profile(profile);
       newProfile.createdAt = profile._id.getTimestamp();
       const savedProfile = await newProfile.save();
       timeStampExtract.push(savedProfile._id.getTimestamp());
    }

【讨论】:

  • 它不起作用,我试过了。 createdAt 没有添加
  • 当我们在架构中使用 { timestamps: true } 时,它会将 createdAt 和 updatedAt 属性添加到文档中。我猜,createdAt 是不可变的,因为它不允许更新值。如果我们将在 createdAt 名称之外添加其他键,例如 created_At 它正在工作
  • 它正在使用保存模型。感谢您的持续帮助。我对答案做了一些小改动。请检查一下
  • 你能帮我解决一下吗:stackoverflow.com/questions/65285364/…
猜你喜欢
  • 2021-08-31
  • 2015-11-08
  • 2021-09-26
  • 1970-01-01
  • 2021-08-20
  • 2017-12-25
  • 2014-08-25
  • 1970-01-01
  • 2019-07-06
相关资源
最近更新 更多