【问题标题】:Mongoose schema set timestamp on nested document猫鼬模式在嵌套文档上设置时间戳
【发布时间】:2020-05-14 04:11:47
【问题描述】:

我的架构如下所示:

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

此架构用于问答论坛,我更喜欢将所有数据嵌入问题文档中。

要求如下:

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

我知道在问题文档上添加时间戳的默认方式:

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

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

【问题讨论】:

  • 您可以将所有架构代码添加到问题中吗?
  • @SuleymanSah 你是什么意思?这就是文档的样子,我仍在设置架构。我不确定是否应该将 createdAt 和 updatedAt 放在架构上。
  • 我的意思是架构中的其他字段。现在它只有名称字段。
  • @SuleymanSah 啊不,这只是说明性的。上面的对象是我的完整 Question 对象。

标签: mongodb mongoose


【解决方案1】:

您还可以将猫鼬模式时间戳选项应用于内部模式。

例如在以下架构中,我将timestamps: true 选项应用于内部出价架构。

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");
    }
  }
);

网址将是这样的: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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 2020-08-18
    • 2017-09-18
    • 2016-06-08
    • 2014-06-22
    • 2022-12-31
    相关资源
    最近更新 更多