Mongoose failing to persist subdocument

After trying to insert into my collection, I noticed that the sub-document is not being saved along with it. This issue has left me puzzled.

This is the scheme/model I am working with:

import { Schema, Document, Model, model } from 'mongoose'

export interface IPerson {
  name: {
    first: string
    last: string
  }
  dob: Date
}

export interface IPersonModel extends IPerson, Document { }

let nameSchema: Schema = new Schema({
  first: String,
  last: String
})
let PersonName = model('PersonName', nameSchema)

export var personSchema: Schema = new Schema({
  name: { child: PersonName.schema },
  dob: Date
}, { timestamps: true })

export const Person: Model<IPersonModel> = model<IPersonModel>('Person', personSchema, 'people')

To pass in data using express and utilize the model, my code looks like this:

import * as bodyParser from 'body-parser'
app.use(bodyParser.json())

app.post('/save/:type', async (req, res) => {
  if (!req.xhr) res.sendStatus(400)
  let p = new Person({
    name: {
      first: req.body.first,
      last: req.body.last
    },
    dob: new Date()
  })
  p.save((err, data) => {
    if (err) console.log(err);
    else console.log('Saved : ', data);
  })
  res.sendStatus(200)
})

Upon saving, the following output is displayed on the terminal:

Saved :  { __v: 0,
    updatedAt: 2017-07-02T14:52:18.286Z,
    createdAt: 2017-07-02T14:52:18.286Z,
    dob: 2017-07-02T14:52:18.272Z,
    _id: 595908a27de708401b107e4b 
}

Despite this, the child section of name remains unsaved. What could be causing this issue?

Answer №1

After some research, I discovered that the key child needed to be replaced with type. Here's the corrected code:

name: { child: PersonName.schema }

should now be changed to

name: { type: PersonName.schema }

Furthermore, instead of passing a schema which creates an _id, I was able to resolve it by passing an object as follows:

name { type: { first: String, last: String } }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to connect List to dropdown in angular

Having trouble connecting dropdown with a List in AngularJS: <select> <option ng-repeat="x in list">{{x}}</option> </select> app.controller('myCtrl', function($scope) { $Scope.list=[{id:1, name='name 1' ...

Creating personalized tags or components by utilizing insertAdjacentHTML in Vue

With the use of insertAdjacentHTML, I am able to create HTML elements such as div and span, but it seems that I cannot generate custom tags like <myComponent> </myComponent>. I understand that insertAdjacentHTML can create HTML elements, but a ...

What are some effective design principles for creating REST APIs in expressjs?

To streamline my code organization, I made the decision to create a methods folder. Within this folder, I store individual JavaScript files for each URL endpoint (such as website.com/billings). //expressJS configuration... const billings = require('. ...

Discovering the selected href URL using JQuery or JavaScript

How can I detect the clicked href URL using JQuery when no ID is being used? For example, if I have a list of links where some redirect to new pages and others call javascript functions to expand a div. What approach should be taken in JQuery/Javascript ...

save the received data to a new document

How can I pass the data returned from the API below to another function in a separate JavaScript file? This question may be similar to others, but those do not involve working with returned results. Please consider this before labeling it as a duplicate. ...

Determine the specific table entry that was clicked on

Currently, I am working on developing a dynamic table that includes a button in one of its columns, which triggers a bootstrap modal. I'm a bit unsure on how to determine which button was clicked and how to populate the table accordingly. Admittedly, ...

What is the best way to utilize typed variables as types with identical names in Typescript?

Utilizing THREE.js with Typescript allows you to use identical names for types and code. For instance: import * as THREE from '/build/three.module.js' // The following line employs THREE.Scene as type and code const scene: THREE.Scene = new THRE ...

The process of authenticating route parameters in Nuxt

I'm having trouble validating route parameters in my page component using the following code: async validate({ params, store }) { await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id) } And here's the corresponding code in the store: ...

The icon in Material UI button is missing from the display

The button is functional, but the icon inside it isn't displaying correctly:https://i.sstatic.net/MXhIH.jpg Here is the code for the button: <Button color="secondary" aria-label="add an alarm"> <AlarmIcon></AlarmI ...

Three.js: Modifying values within dat.GUI is not allowed

I have added a "comboBox" to my dat.GUI instance in order to select possible values. However, when I run my application, the dat.GUI appears with the comboBox but it seems to be frozen - I cannot change its default value. Below is the code snippet that dem ...

Retrieving information from the API to populate a child component in Next.js

I have been developing a header component and here's the code snippet: import style from '../../styles/header.css'; import '../../styles/globals.css'; export default function Header({data}){ const [showMe, setShowMe] = useStat ...

Create a customizable Tree structure that includes checkboxes for each item and features drag

I am currently working on incorporating a Tree view with checkboxes and drag & drop functionality in Vue. However, I am unsure of where to begin. While I have successfully implemented checkboxes, I am struggling to figure out how to enable the feature whe ...

Ways to manage an element that has been loaded using the load query function

After implementing the query load function to update posts on the homepage, I was able to display the most up-to-date posts. However, a new issue arose: Whenever I updated all posts without refreshing the entire page, I needed a way to control the element ...

Display a loading animation before the page loads upon clicking

$("#button").click(function(){ $(document).ready(function() { $('#wrapper').load('page.php'); }); }); <div id="wrapper"></div> <div id="button">click me</div> I would like to display a loading ic ...

Incorporate React Components into a traditional HTML, CSS, and JavaScript project

Can I incorporate a React Native Component (https://www.npmjs.com/package/react-native-gifted-chat) into my vanilla JavaScript project? Is it feasible to embed a React Native component within a vanilla JavaScript project? If yes, then what is the process ...

The autoRemoveInterval feature of connect-mongo is malfunctioning and not functioning as intended

Here is the code snippet that I am using with express.js and express-session: app.use(session({ store: new MongoStore({ mongooseConnection: db, autoRemove: 'interval', autoRemoveInterval: 1 // 1 minute (min) }), secret: 'so ...

Running the nestjs build command is impossible without the existence of the node_modules folder

Currently, I am in the process of creating a Nestjs micro-service and everything is going smoothly. To run the build found within the dist folder, I use the command below: node dist/main.js However, I encountered a problem where this command does not exec ...

Changing position of element upon appearance of span in React

Currently, I am working with React and facing an issue where a span element appears whenever a user hovers over a text element. The problem is that the existing text shifts leftwards when the span appears (to the right of the text). The desired behavior ...

"Adjusting the width of columns in a Datatable

I have arranged a data table with multiple rows and columns, and I am seeking guidance on how to increase the width of the "Tel. 1, Tel. 2, and Fecha" columns to ensure that the text appears on a single line. I've attempted adjusting the s width and t ...

Sort orders by the current day during MongoDB business hours

Currently, I am attempting to replicate the functionality of the Google "Hours" dropdown that is displayed on a location listing. https://i.sstatic.net/JbhpS.png The structure of a business hours array appears as follows: [ {id: 5d991d1208ac396803a9 ...