Objects inside collections

Hello,

I’m trying to have a collection with an object inside it.
E.g if I have a collection of
Cars = new Mongo.Collection('cars');

And a simple schema of:

CarsSchema= new SimpleSchema({
	engine: {
		type: String
	},

	brakes: {
		type: String
	}, //etc
});

I want to have something like this

CarsSchema= new SimpleSchema({
	engine: {
        type: Object {
                          name: String ,
                          make: String,
                          price: Number,	
        },

	brakes: {
		type: Object {
                          name: String ,
                          make: String,
                          price: Number,
	}, //etc
});

What’s the best way of doing this?

Also, when it comes to inserting data into these objects, how can I do it?

Would it be something similar to
Cars.engine.insert({ name: inputName, make: inputMake, price: inputPrice)};
If not, how can I insert?

I want to stay away from Autoform, as I’m still in the process of learning, and I couldn’t find a good tutorial about Objects in Collections.

I truly appreciate the time, thank you!

MongoDB and it’s Collections are designed to hold arbitrary objects (called documents), so it’s very easy to do what you want to do here.

To insert an object, you just pass the whole object as the parameter to the insert method on that collection:

const Cars = new Mongo.Collection('cars');
Cars.insert({
    engine: { name: 'foo', make: 'bar', price: 2000 },
    brakes: { name: 'disk', make: 'Brakes R Us', price: 400 },
    // etc...
});

If you want to update just one part of the object later on, you will want to use an Update Operator to select the part you want to update

// Example, lets increase the price of the disk brakes
Cars.update({ _id: idToUpdate }, { $set: { 'brakes.price': 600 } })

Note the operator $set and the dot delimited string used to reach deep into the object to update one property.

The MongoDB documentation is useful for more information on different queries.


Since you also mention using SimpleSchema, there are a couple of ways to do what you want:

  1. With everything like so:
const carSchema = new SimpleSchema({
    engine: Object,
    'engine.name': String ,
    'engine.make': String,
    'engine.price': Number,
    brakes: Object,
    'brakes.name': String,
    'brakes.make': String,
    'brakes.price': Number,
    // etc...
});

Note that for deeper keys it uses the same dot delimited string notation that MongoDB uses

  1. Or save repetition by using a sub-schema (If all the car parts are objects with the same keys)
const partSchema = new SimpleSchema({
    name: String,
    make: String,
    price: Number,
});
const carSchema = new SimpleSchema({
    engine: partSchema,
    brakes: partSchema,
    // etc...
});

Here’s the documentation for simpl-schema

2 Likes

This is exactly what i’m looking for! Thank you so much.