Vous pouvez également appliquer les options d'horodatage du schéma mongoose aux schémas internes.
Par exemple dans le schéma suivant, j'ai appliqué timestamps: true
option au schéma d'enchères internes.
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;
Testons-le maintenant :
J'ai créé un document de forum avec le code suivant :
const Forum = require("../models/forum");
router.post("/forums", async (req, res) => {
const result = await Forum.create(req.body);
res.send(result);
});
Corps de la requête :
{
"title": "Title 1",
"biddings": [
{
"biddingId": "bidding1",
"biddingPoints": 10
},
{
"biddingId": "bidding2",
"biddingPoints": 30
}
]
}
Réponse :(comme vous le voyez, les horodatages sont appliqués aux documents parent et sous-document)
{
"_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
}
Maintenant, mettons à jour le point d'enchère avec le _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");
}
}
);
L'URL ressemblera à ceci :http://.../forums/5e3073b3a2890b03b029e92c/biddings/5e3073b3a2890b03b029e92e
Requête :(cela signifie que je veux mettre à jour les points à 50 de l'enchère avec _id:5e3073b3a2890b03b029e92e
:
{
"points": 50
}
Réponse :(comme vous le voyez updatedAt
la valeur du champ de l'enchère mise à jour a changé automatiquement de 2020-01-28T17:47:31.376Z
au 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
}