无法更新猫鼬中的createdAt属性? [英] unable to update the createdAt property in mongoose?
问题描述
您好,所有专家
可能是问题似乎重复,但我的业务案例却几乎没有什么不同,请忍受.
Might be question seem duplicate but mine business case is little different, Please, bear with me.
我正在使用其他开发人员定义的旧架构,其中缺少createdAt
和updatedAt
属性.所以我通过添加{ timestamps: true }
更新了架构.每当我创建新文档时,就没有问题.它按预期工作,但是现有/旧文档在那里,因此我尝试通过编写单独的脚本并从_id
属性(如_id.getTimestamp()
)读取创建的时间来添加createdAt
属性.我能够从_id中提取创建的时间,但是无法在现有文档中添加createdAt
属性.旧文档/数据非常重要,但是企业希望为旧文档增加createdAt
属性.
I am working old Schema defined by other developer where createdAt
and updatedAt
properties are missing. so I have updated the schema by adding the { timestamps: true }
. whenever I am creating new document then there is no problem. it is working as expected but existing/old documents are there so I am trying to add createdAt
properties by writing separate script and reading created time from _id
property like _id.getTimestamp()
. I am able to extract created time from _id but unable to add createdAt
property in existing document. old documents/data is very crucial but business is expecting to add createdAt
propery to old document.
我正在使用猫鼬NPM 库,版本为:"mongoose": "^5.9.16",
I am using mongoose NPM library and version is : "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
Script to add createdAt property with extracting the timestamp from _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 是不可变的吗?
is By-default createdAt is immutable ?
有人可以帮忙吗?这将是很大的帮助.
Could some someone help with it? It will be great help.
感谢所有专家
推荐答案
由于某些文档是在timestamps
选项设置为false(这是默认值)时创建的,所以猫鼬将不知道这些时间戳.因此,item._id.getTimestamp()
将返回未定义.
Since some of the documents were created when the timestamps
option was set to false (this is the default value) mongoose will not know those timestamps. Hence, item._id.getTimestamp()
will return undefined.
您可以做的是重新创建createdAt
不存在的条目.如果启用了该选项,猫鼬将自动生成时间戳并将其设置为当前时间戳:
What you can do, is to recreate the entries where createdAt
does not exist. Mongoose will then automatically generate the timestamps and set them to the current timestamp, if the option is enabled:
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属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!