Node.js 是否有一种方法可以跟踪模型中更改的时间和实体
基本上,当调用update方法时,我会尝试在特定模型中更改时间和实体 这是我想要跟踪的模型:Node.js 是否有一种方法可以跟踪模型中更改的时间和实体,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,基本上,当调用update方法时,我会尝试在特定模型中更改时间和实体 这是我想要跟踪的模型: const mongoose = require("mongoose"); const modelSchema = mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "User", }, name: {
const mongoose = require("mongoose");
const modelSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
name: {
type: String,
required: true,
},
note1: String,
note2: String,
note3: String,
images: {
type: Array,
required: true
},
status: {
enum: ['draft', 'pending_quote', 'pendong_payment', 'in_production', 'in_repair', 'pemding_my_review', 'fulfilled'],
type: String,
default: "draft"
},
price: {
type: mongoose.Schema.Types.ObjectId,
ref: "Price",
}
}, {
timestamps: true,
})
module.exports = mongoose.model("Model", modelSchema)
这是我用来更新状态的方法:
exports.updateModel = async (req, res) => {
try {
let id = req.params.id;
let response = await Model.findByIdAndUpdate(id, req.body, {
new: true
})
res.status(200).json({
status: "Success",
data: response
})
} catch (err) {
res.status(500).json({
error: err,
msg: "Something Went Wrong"
})
}
}
您可以在架构中添加新字段,如:
logs:[{
entity: String,
timeStamp: Date
}]
然后根据当前代码对其进行更新:
let id = req.params.id;
// I don't know whats in the req.body but assuming that it
// has the correct structure when passed from the front end
let response = await Model.findByIdAndUpdate(id,
{
$set:req.body,
$push:{logs:{entity:'your entity name here',timeStamp:new Date()}}
}, {
new: true
})
您希望在哪些字段中保存日期和实体详细信息?我可以创建一个更改数组来存储这些内容。我已经为您发布了一个答案。实际上,我希望这是自动化的,因为一旦状态更新,its会将更新的状态和时间推送到日志数组中。执行此操作时,`req.body.logs.push{entity:status,timeStamp:new Date}`表示推送未定义这是我在POSTMAN中发出请求的方式:{status:pending_quote}因此,如果您console.logreq.body,它将显示:{status:pending_quote}?