Mongoose模式在嵌套文档上设置时间戳

l5tcr1uw  于 2023-03-18  发布在  Go
关注(0)|答案(2)|浏览(129)

我有一个如下所示的模式:

{
  "_id": "5073c76a23ce3abf0f000001",
  "asker": {
    "userId": "fooId",
    "firstName": "foo",
    "lastName": "bar",
    "points": "10",
    "aboutMe": "Something about me"
  },
  "isBounty": false,
  "tags": ["mongodb", "nosql", "mongodb-query"],
  "title": "Is there merit to adding flat properties additional to a duplicate nested",
  "descriptionMd": "Question description",
  "offeredPoints": 10,
  "slug": "is-there-merit-to-adding-flat-properties-additional-to-a-duplicate-nested",
  "biddings": [{
    "biddingId": "_biddingId",
    "respondent": {
      "userId": "fooId",
      "firstName": "foo",
      "lastName": "bar",
      "points": "10",
      "aboutMe": "Something about me"
    },
    "biddingPoints": 10,
    "createdAt": "2019-03-21T08:00:00",
    "lastUpdatedAt": "2019-03-21T08:00:00"
  }],
  "acceptedBidding": "_biddingId",
  "answers": [
    {
      "respondent": {
        "address": {
          "userId": "fooId",
          "firstName": "foo",
          "lastName": "bar",
          "points": "10",
          "aboutMe": "Something about me"
        }
      },
      "answerTextMd": "Answer 1",
      "reviewRequested": true,
      "reviewer": {
        "userId": "fooId",
        "firstName": "foo",
        "lastName": "bar",
        "points": "10",
        "aboutMe": "Something about me"
      },
      "reviewStatus": "ANSWER_ACCEPTED",
      "createdAt": "2019-03-21T08:00:00",
      "lastUpdatedAt": "2019-03-21T08:00:00"
    }
  ],
  "createdAt": "2019-03-21T08:00:00",
  "lastUpdatedAt": "2019-03-21T08:00:00"
}

这个模式是为问答论坛设计的,我更喜欢将所有数据嵌入到问题文档中。
所需经费如下:

  • 在问题文档上设置创建和更新的时间戳
  • 时间戳应该放在嵌套投标和答案以及

我知道在Question文档上添加时间戳的默认方法:

const mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );

如何在更新时将时间戳动态地放在嵌套文档上?
有没有建议的方法,或者我应该自己把字段放在那里,然后手动更新它们?

gmol1639

gmol16391#

您还可以将mongoose模式时间戳选项应用于内部模式。
例如,在下面的模式中,我将timestamps: true选项应用于内部biddings模式。

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;

现在我们来测试一下:
我用下面的代码创建了一个论坛文档:

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

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

请求正文:

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

响应:(如您所见,时间戳同时应用于父文档和子文档)

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

现在,让我们使用_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");
    }
  }
);

URL将如下所示:http://.../forums/5e3073b3a2890b03b029e92c/biddings/5e3073b3a2890b03b029e92e
请求:(这意味着我想用_id:5e3073b3a2890b03b029e92e更新点50出价:

{
    "points": 50
}

响应:(如您所见,更新后投标的updatedAt字段值自动从2020-01-28T17:47:31.376Z更改为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
}
dsekswqp

dsekswqp2#

整个代码是完美的,但内部findByIdandUpdate查询使用以下代码将biddingID从转换为对象ID。
数组筛选器:[{“内部._ID”:新建 Mongoose 。类型。对象ID(请求参数。投标ID)}]

相关问题