无法更新猫鼬中的createdAt属性?

问题描述

你好,所有专家,

可能是问题似乎重复,但我的业务案例却几乎没有什么不同,请忍受。

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

我正在使用猫鼬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选项设置为false(这是默认值)时创建的,所以猫鼬将不知道这些时间戳。因此,item._id.getTimestamp()将返回未定义。

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

    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());
    }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...