![](/img/trans.png)
[英]Cypress: How can I get the timestamp of when Cypress start to record in headless mode?
[英]How can I record a timestamp of when a record is created in Mongoose schema?
我正在構建一個允許用戶在網頁上輸入記錄的應用程序。 我想顯示提交每條記錄的日期/時間,我嘗試了幾種不同的方法,最后以我想要的格式顯示日期/時間,但似乎時間戳是在服務器時記錄的啟動而不是在添加記錄時啟動。 我正在使用 moment.js 進行格式化
這是我的架構
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const moment = require("moment");
var d = new Date();
var formattedDate = moment(d).format("MM-DD-YYYY, h:mm:ss a");
let codeSchema = new Schema({
code: {
type: String
},
createdAt: {
type: String,
default: formattedDate
},
},
{
collection: "codes"
}
);
module.exports = mongoose.model("Code", codeSchema);
這是記錄的外觀,除了日期和時間是我啟動服務器的時間而不是實際添加文檔的時間
123456789789 12-09-2021, 12:59:33 pm
有趣的問題。 我在應用程序中使用 mongoose 並沒有看到這個問題。 請參閱下面的架構:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const schema = new Schema({
createdBy: Object,
created: { type: Date, default: Date.now },
matchName: { type: String, required: true },
matchType: { type: String, required: true },
matchActive: { type: Boolean, default: false },
matchPrivate: { type: Boolean, default: true },
matchTime: { type: String, required: true },
matchDate: { type: String, requried: true },
matchPassword: String,
matchMembers: [],
course: Object,
subCourse: Object,
par: { type: Number, required: true },
numberOfHoles: { type: Number, required: true },
frontBackNine: { type: String, required: true, default: null },
completed: { type: Boolean, default: false },
compeletedOn: { type: Date },
winner: { type: String },
startingHole: { type: Number, default: 1 },
scorecardSettings: { type: String, required: true },
tournamentGroups: { type: Array, default: [] },
});
module.exports = mongoose.model("Matches", schema);
但是我沒有使用 moment.js。
這里有兩個想法:
Date.now
代替時刻格式化的日期。 這只是為了查看是否是導致問題的時刻,並且不會實際為您提供解決方案
考慮何時評估和分配該變量; 是在創建模式時,只發生一次。 在任何情況下,您都應該在保存記錄時分配該值,並像其他任何值一樣分配該值。
但是,moongose 已經可以選擇在創建和更新記錄時為記錄分配時間戳。 在這里查看: https://mongoosejs.com/docs/guide.html#timestamps
您的代碼應如下所示:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const codeSchema = new Schema({
code: {
type: String
},
createdAt: {
type: String,
default: formattedDate
},
},
{
collection: "codes",
timestamps: true
}
);
module.exports = mongoose.model("Code", codeSchema);
關於格式,我強調建議在使用數據的最后一點之后注意這一點。
您正在分配一個預定義的值,這就是它不起作用的原因,您應該創建一個 function 並將 function 分配為默認值以獲取文檔時的值。
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const moment = require("moment");
var createdAt = function(){
var d = new Date();
var formattedDate = moment(d).format("MM-DD-YYYY, h:mm:ss a");
return formattedDate;
};
let codeSchema = new Schema({
code: {
type: String
},
createdAt: {
type: String,
default: createdAt
},
},
{
collection: "codes"
}
);
module.exports = mongoose.model("Code", codeSchema);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.