Você também pode aplicar opções de carimbos de data/hora do esquema mangusto aos esquemas internos.
Por exemplo, no esquema a seguir, apliquei
timestamps: true
opção para o esquema de lances internos. 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;
Agora vamos testar:
Criei um documento do fórum com o seguinte código:
const Forum = require("../models/forum");
router.post("/forums", async (req, res) => {
const result = await Forum.create(req.body);
res.send(result);
});
Corpo da solicitação:
{
"title": "Title 1",
"biddings": [
{
"biddingId": "bidding1",
"biddingPoints": 10
},
{
"biddingId": "bidding2",
"biddingPoints": 30
}
]
}
Resposta:(como você vê, os carimbos de data/hora são aplicados aos documentos pai e sub)
{
"_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
}
Agora vamos atualizar o ponto de lance com o
_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");
}
}
);
A url será assim:
http://.../forums/5e3073b3a2890b03b029e92c/biddings/5e3073b3a2890b03b029e92e
Solicitação:(significa que quero atualizar os pontos para 50 dos lances com
_id:5e3073b3a2890b03b029e92e
:{
"points": 50
}
Resposta:(como você vê
updatedAt
o valor do campo do lance atualizado foi alterado automaticamente de 2020-01-28T17:47:31.376Z
para 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
}