jul*_*isz 5 arrays mongoose mongodb node.js
我在 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
Run Code Online (Sandbox Code Playgroud)
这是我的猫鼬模式
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 }
),
},
],
});
Run Code Online (Sandbox Code Playgroud)
每次我添加一个新人时,疫苗数组都会获得一个带有时间戳的新对象,如您所见,在我的 js 文件中,我使用以下代码:
const addPerson = (person) => {
const myPerson= new Model(person);
return myPerson.save();
};
Run Code Online (Sandbox Code Playgroud)
然后,当我为同一个人添加新疫苗时,这不会获得时间戳,我将使用以下代码:
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;
};
Run Code Online (Sandbox Code Playgroud)
这是我体内疫苗阵列的内容:
[ { vaccine: '5f72c909594ee82d107bf870', dose: 'Primera' } ]
问题是我没有关于下一个时间戳的结果,正如您在我的 mongo atlas 文档中看到的那样:
1:Object
dose:Array
_id:5f893a9ca98e97188c93fea8
vaccine:5f70259796f7ed21e85be523
2:Object
dose:Array
_id:5f893acda98e97188c93fea9
vaccine:5f7023ad96f7ed21e85be521
Run Code Online (Sandbox Code Playgroud)
这是在子文档或子模式中实现时间戳的最佳方法吗?
我会很感激你的回答,谢谢
您可以对内部模式使用猫鼬模式时间戳选项
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;
Run Code Online (Sandbox Code Playgroud)