nuxer
nuxer

Reputation: 478

mongoose subdocument array not saving the entire object?

Here is my problem I have two schemas one nested in another as an array. I am trying to push into the array and save the subdocument but it is not saving properly, I get an object that is saved but none of the fields are saved except for its _id. Do I have to save each model individually first? What is the issue here?

Here are my two schemas:

import mongoose from "mongoose";
import {contactSchema} from "./ContactSchema"

export const bigSchema = new mongoose.Schema({
  testField: {
    type: String,
    required: true,
  },
  contacts: [{ contactSchema }],
  }
});

export default mongoose.model("Big", bigSchema);

import mongoose from "mongoose";

export const contactSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  age: {
    type: number,
    required: false,
  }
});

export default mongoose.model("Contact", contactSchema);

Here is my code that I use to push to the array of contacts.

 public async saveContact(
    testField: string,
    name: string,
    age: number,
  ) {
    const newContact = new Contact({
      name: name,
      age: age,
    });

    console.log(newContact);
    return UserContacts.findOneAndUpdate(
      {
        testField: testField,
      },
      { $push: { contacts: newContact } },
      { new: true, upsert: true }
    );
  }

However when I check my database, this is what I see instead. There is an objectId but not what I expect to see, which is a list of Contact subdocuments inside my "Big" document

{
    "_id" : ObjectId("XXXX"),
    "testField" : "XXXXX",
    "contacts" : [ 
        {
            "_id" : ObjectId("XXXXX")
        }
    ],
    "__v" : 0
}

Upvotes: 0

Views: 1625

Answers (1)

chrispytoes
chrispytoes

Reputation: 1889

export const bigSchema = new mongoose.Schema({
  testField: {
    type: String,
    required: true,
  },
  contacts: [{ contactSchema }],
  }
});

should be:

export const bigSchema = new mongoose.Schema({
  testField: {
    type: String,
    required: true,
  },
  contacts: [contactSchema],
  }
});

Try that and see what happens.

Edit: Also, if you intend for contacts to be an array of references to the Contact model, then you need to do this instead:

export const bigSchema = new mongoose.Schema({
  testField: {
    type: String,
    required: true,
  },
  contacts: [{type: mongoose.Schema.Types.ObjectId, ref: 'Contact'}],
  }
});}

This will make contacts an array of Contact IDs, so you're not duplicating any data, but just referencing the contacts in their collection. docs

Upvotes: 1

Related Questions