Search code examples
javascripthtmlmeteorschemameteor-collection2

Embedded Schema Inserting Blank in Meteor using Collection2


I am fairly new to meteor and attempting to insert to a collection using a model that uses embedded schemas. The content in the embedded schema is not being inserted into the db and is instead an empty entry.

The main model is being attached to the collection.

Guests = new Mongo.Collection('guests');

Schema = {}

Guests.attachSchema(new SimpleSchema({
    BasicInformation : {
        type: Schema.basicInfo,
        optional: false,
    },
})

The basicInfo schema is defined as follows.

Schema.basicInfo = new SimpleSchema({
    firstName: {
        type: String,
    },
    middleName: {
        type: String,
    },
    lastName: {
        type: String,
    }
})

I am using this to insert in the collection on a common js file.

Guests.insert({
    BasicInformation: {
        firstName: 'First Name',
        middleName: 'Middle Name', 
        lastName: 'Last Name'
    },
})

If I remove the schema and add the fields in the main model instead of using an embedded schema, then it does get inserted. Not sure what’s up…help!


Solution

  • Welcome to Stack Overflow. And, as @Jankapunkt says, please put your code as formatted blocks in your question. Links to pictures hosted elsewhere may not work if the images get deleted. It's also easier for us to fix your code and show you what it should look like.

    I think at the time you set up your schema, the Schema Object is empty. You add info to it later, but it's too late at that point. If you put the code in your question I can show you how, but I'm not willing to retype it for you.

    UPDATE: Good work. You need to populate the Schema object before you attach it to the table:

    Guests = new Mongo.Collection('guests');
    
    Schema = {} // Right now the object is empty
    
    Schema.basicInfo = new SimpleSchema({ // So we add the sub-schema
        firstName: {
            type: String,
        },
        middleName: {
            type: String,
        },
        lastName: {
            type: String,
        }
    })
    
    Guests.attachSchema(new SimpleSchema({ 
        BasicInformation : {
            type: Schema.basicInfo, // previously this was undef, now it is correct
            optional: false,
        },
    })
    

    That should work for you.