node.js - 无法更新 Mongoose 中的createdAt属性?

标签 node.js mongodb express mongoose data-migration

各位专家大家好,

问题可能看起来重复,但我的业务案例略有不同,请耐心等待。

我正在使用其他开发人员定义的旧架构,其中 createdAtupdatedAt属性缺失。所以我通过添加 { timestamps: true } 更新了架构。每当我创建新文档时就没有问题。它按预期工作,但现有/旧文档在那里,所以我尝试添加 createdAt通过编写单独的脚本并从_id读取创建时间来属性属性如 _id.getTimestamp() 。我能够从 _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 选项设置为 false(这是默认值)时创建的,mongoose 将不知道这些时间戳。因此,item._id.getTimestamp() 将返回未定义。

您可以做的是重新创建 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());
    }

关于node.js - 无法更新 Mongoose 中的createdAt属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64496424/

相关文章:

node.js - 使用 Istanbul 和 Mocha 覆盖 ES6 代码

json - 如何向 Node/Express 站点添加代理?

mongodb - 如何使用电机的 open_download_stream 与 FastAPI 的 StreamingResponse 一起工作?

mongodb - 无法在来自市场的 github 操作中使用工作流环境变量(通过构建矩阵)

node.js - 未登录时尝试访问路由时使用 connect-flash 消息重定向

javascript - 套接字在前端找不到源文件

node.js - express.static 处理根 url 请求

json - Twitter 流 api OAuth 未经授权

node.js - NodeJS 8.10.0 - Azure (iisnode) - 在严格模式之外尚不支持 block 范围声明(let、const、函数、类)

mongodb - 如何使用 typegoose 自动填充 Mongoose