sql >> Base de Datos >  >> NoSQL >> MongoDB

El esquema de Mongoose establece la marca de tiempo en el documento anidado

También puede aplicar las opciones de marcas de tiempo del esquema mongoose a los esquemas internos.

Por ejemplo, en el siguiente esquema, apliqué timestamps: true opción al esquema de ofertas internas.

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;

Ahora vamos a probarlo:

Creé un documento de foro con el siguiente código:

const Forum = require("../models/forum");

router.post("/forums", async (req, res) => {
  const result = await Forum.create(req.body);
  res.send(result);
});

Cuerpo de la solicitud:

{
    "title": "Title 1",
    "biddings": [
        {
            "biddingId": "bidding1",
            "biddingPoints": 10
        },
        {
            "biddingId": "bidding2",
            "biddingPoints": 30
        }
    ]
}

Respuesta:(como puede ver, las marcas de tiempo se aplican tanto a los documentos principales como a los secundarios)

{
    "_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
}

Ahora actualicemos el punto de oferta con el _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");
    }
  }
);

La URL será así:http://.../forums/5e3073b3a2890b03b029e92c/biddings/5e3073b3a2890b03b029e92e

Solicitud:(significa que quiero actualizar los puntos a 50 de la subasta con _id:5e3073b3a2890b03b029e92e :

{
    "points": 50
}

Respuesta:(como ves updatedAt el valor del campo de la oferta actualizada cambió automáticamente de 2020-01-28T17:47:31.376Z a 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
}