'How to define a schema that has nested arrays of objects
Update: Wasn't using the collection object in the Schema for mongoose to specify what collection in the database to look at. Once I added the following to the mongoose.Schema it works fine.
{
collection: "maintenances"
}
New to mongoose schemas and having trouble with a more advanced object in MongoDB. Getting simple schemas to work seems fine but I have the following MongoDB schema that I am trying to replicate with a mongoose schema.
{
"_id": {
"$oid": "61310bacd8195bf421751c16"
},
"jiraId": "NA-151",
"summary": "jira summary, trimmed to 50 chars",
"reason": "maint reason",
"date": {
"$date": "2021-07-01T05:00:00.000Z"
},
"createdDate": {
"$date": "2021-08-01T05:00:00.000Z"
},
"pre": [
{
"hostname": "device1",
"displayName": "device description",
"mopData": [
{
"command": "show clock",
"result": "this is the show clock command pre"
},
{
"command": "show version",
"result": "16.12.1"
}
]
}
],
"post": [
{
"hostname": "device1",
"displayName": "device description",
"mopData": [
{
"command": "show clock",
"result": "this is the show clock command post"
},
{
"command": "show version",
"result": "16.12.4"
}
]
}
],
"deviceCount": 1
}
I have tried several variations of js but its keeps returning empty arrays when doing a .find() on the collection.
import mongoose from "mongoose";
import shortid from "shortid"
import {Main} from "next/document";
const {String, Number, Date} = mongoose.Schema.Types;
const MaintenanceMopData = new mongoose.Schema({
command: {
type: String,
required: true
},
result: {
type: String,
required: true
}
})
const MaintenancePrePostSchema = new mongoose.Schema({
hostname: {
type: String,
required: true
},
displayName: {
type: String,
required: true
},
mopData: [MaintenanceMopData],
})
const MaintenanceSchema = new mongoose.Schema({
jiraId: {
type: String,
required: true
},
summary: {
type: String,
required: true
},
reason: {
type: String,
required: true
},
maintDate: {
type: Date,
required: false
},
createdDate: {
type: Date,
required: false
},
pre: [MaintenancePrePostSchema],
post: [MaintenancePrePostSchema],
deviceCount: {
type: Number,
required: false
}
})
export default mongoose.models.Maintenance || mongoose.model('Maintenance', MaintenanceSchema)
Is this correct or what is the proper way to implement schema that has nested arrays of objects?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
