gpt4 book ai didi

node.js - 将时间戳添加到 mongoose 中的新子文档或子模式

转载 作者:行者123 更新时间:2023-12-04 13:11:49 25 4
gpt4 key购买 nike

我在 mongo atlas 中有这份文件

_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

这是我的 Mongoose 模式
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 atlas 文档中看到的:
1:Object
dose:Array
_id:5f893a9ca98e97188c93fea8
vaccine:5f70259796f7ed21e85be523
2:Object
dose:Array
_id:5f893acda98e97188c93fea9
vaccine:5f7023ad96f7ed21e85be521
这是在子文档或子模式中实现时间戳的最佳方法吗?
我会很感激你的回答,谢谢👏

最佳答案

您可以使用 Mongoose 架构时间戳 的选项内部架构

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;
更多 Mongoose schema set timestamp on nested document

关于node.js - 将时间戳添加到 mongoose 中的新子文档或子模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64385442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com