Anda juga dapat menerapkan opsi stempel waktu skema luwak ke skema dalam.
Misalnya dalam skema berikut, saya menerapkan timestamps: true
opsi untuk skema penawaran dalam.
const mongoose = require("mongoose");
const forumSchema = new mongoose.Schema(
{
title: { type: String, required: true },
biddings: [
{
type: new mongoose.Schema(
{
biddingId: String,
biddingPoints: Number
},
{ timestamps: true }
)
}
]
},
{ timestamps: true }
);
const Forum = mongoose.model("Forum", forumSchema);
module.exports = Forum;
Sekarang mari kita uji:
Saya membuat dokumen forum dengan kode berikut:
const Forum = require("../models/forum");
router.post("/forums", async (req, res) => {
const result = await Forum.create(req.body);
res.send(result);
});
Isi permintaan:
{
"title": "Title 1",
"biddings": [
{
"biddingId": "bidding1",
"biddingPoints": 10
},
{
"biddingId": "bidding2",
"biddingPoints": 30
}
]
}
Tanggapan:(seperti yang Anda lihat, stempel waktu diterapkan pada dokumen induk dan subdokumen)
{
"_id": "5e3073b3a2890b03b029e92c",
"title": "Title 1",
"biddings": [
{
"_id": "5e3073b3a2890b03b029e92e",
"biddingId": "bidding1",
"biddingPoints": 10,
"createdAt": "2020-01-28T17:47:31.376Z",
"updatedAt": "2020-01-28T17:47:31.376Z"
},
{
"_id": "5e3073b3a2890b03b029e92d",
"biddingId": "bidding2",
"biddingPoints": 30,
"createdAt": "2020-01-28T17:47:31.376Z",
"updatedAt": "2020-01-28T17:47:31.376Z"
}
],
"createdAt": "2020-01-28T17:47:31.376Z",
"updatedAt": "2020-01-28T17:47:31.376Z",
"__v": 0
}
Sekarang mari perbarui titik penawaran dengan _id:5e3073b3a2890b03b029e92e
router.put("/forums/:forumId/biddings/:biddingId",
async (req, res) => {
let points = req.body.points;
try {
let result = await Forum.findByIdAndUpdate(
req.params.forumId,
{
$set: {
"biddings.$[inner].biddingPoints": points
}
},
{
arrayFilters: [{ "inner._id": req.params.biddingId }],
new: true
}
);
if (!result) return res.status(404);
res.send(result);
} catch (err) {
console.log(err);
res.status(500).send("Something went wrong");
}
}
);
Urlnya akan seperti ini:http://.../forums/5e3073b3a2890b03b029e92c/biddings/5e3073b3a2890b03b029e92e
Request:(artinya saya mau update poin ke 50 dari penawaran dengan _id:5e3073b3a2890b03b029e92e
:
{
"points": 50
}
Tanggapan:(seperti yang Anda lihat updatedAt
nilai bidang dari penawaran yang diperbarui berubah secara otomatis dari 2020-01-28T17:47:31.376Z
ke 2020-01-28T17:50:03.855Z
)
{
"_id": "5e3073b3a2890b03b029e92c",
"title": "Title 1",
"biddings": [
{
"_id": "5e3073b3a2890b03b029e92e",
"biddingId": "bidding1",
"biddingPoints": 50,
"createdAt": "2020-01-28T17:47:31.376Z",
"updatedAt": "2020-01-28T17:50:03.855Z" ==> UPDATED
},
{
"_id": "5e3073b3a2890b03b029e92d",
"biddingId": "bidding2",
"biddingPoints": 30,
"createdAt": "2020-01-28T17:47:31.376Z",
"updatedAt": "2020-01-28T17:47:31.376Z"
}
],
"createdAt": "2020-01-28T17:47:31.376Z",
"updatedAt": "2020-01-28T17:50:03.855Z",
"__v": 0
}