将时间戳添加到新的子文档或猫鼬子模式中

时间:2020-10-16 08:20:17

标签: node.js arrays mongodb mongoose

我在mongo地图集中有这份文件

_id: 5f8939cbedf74e363c37dd86,
firstname: "Person",
lastname: "Person lastname",
sex: "Masculino",
age: "20",
birthDay: 2020-10-07T00:00:00.000+00:00,
vaccines: Array
 0:Object
  dose: Array
   _id: 5f8939cbedf74e363c37dd87
   vaccine:5f7023ad96f7ed21e85be521
   createdAt:2020-10-16T06:12:27.726+00:00
   updatedAt:2020-10-16T06:12:27.726+00:00
 1:Object
  dose:Array
  _id:5f893a9ca98e97188c93fea8
  vaccine:5f70259796f7ed21e85be523
 2:Object
  dose:Array
  _id:5f893acda98e97188c93fea9
  vaccine:5f7023ad96f7ed21e85be521

这是我的猫鼬模式

const mySchema = new Schema({
  firstname: {
    type: String,
    required: true,
  },
  lastname: {
    type: String,
    required: true,
  },
  sex: {
    type: String,
    required: true,
  },
  age: {
    type: String,
    required: true,
  },
  birthDay: {
    type: Date,
    required: true,
  },
  vaccines: [
    {
      type: new Schema(
        {
          vaccine: {
            type: Schema.ObjectId,
            ref: "Vaccine",
          },
          dose: Array,
        },
        { timestamps: true }
      ),
    },
  ],
});

每当我添加一个新人时,疫苗阵列都会获得一个带有时间戳的新对象,如您所见,在我的js文件中,我使用以下代码:

const addPerson = (person) => {
  const myPerson= new Model(person);
  return myPerson.save();
};

然后,当我为同一个人添加新疫苗时,却没有时间戳记,我正在为此使用以下代码:

const addPersonVaccine = async ({ params, body }) => {
  if (!params) return Promise.reject("Invalid ID");
  const vaccines = [body];
  const foundPerson = await Model.updateOne(
    {
      _id: params,
    },
    {
      $push: {
        vaccines: vaccines,
      },
    }
  );
  return foundPerson;
};

这就是我体内的疫苗阵列所具有的: [ { vaccine: '5f72c909594ee82d107bf870', dose: 'Primera' } ]

问题是,关于下一个时间戳,我没有任何结果,如您在我的mongo地图集文档中所见:

1:Object
  dose:Array
  _id:5f893a9ca98e97188c93fea8
  vaccine:5f70259796f7ed21e85be523
 2:Object
  dose:Array
  _id:5f893acda98e97188c93fea9
  vaccine:5f7023ad96f7ed21e85be521

这是在子文档或子模式中实现时间戳的最佳方法吗?

感谢您的回答,谢谢!

0 个答案:

没有答案