domingo, 9 de diciembre de 2012

Inserting rows with schemas which have a required relationship with other schemas in MongoDB (NoSQL)


Inserting rows into a table that have a relationship with other tables using foreign keys, it is a very basic functionality in SQL. On the other hand, in NoSQL engines where the queries are managed in documents (or views) instead of a relational way, it is not very common, but it is still necessary to have.


That is why I needed to perform these operations in a project where I am using Mongoose (MongoDB - NoSQL engine - for Node.js) and it was not a trivial issue.

In some forums pointed out that the relationships between tables (in NoSQL, schema) had to be defined just naming the schema in [] characters (for arrays) within the column such as:

var CountrySchema = new Schema({
countryName: { type: String, required: true },
cities: { type: [CitySchema], required: true }, // Works!
mainCity: { type: Schema.ObjectId, ref: "City", required: true } // Does not work!
});

But this is not working when you do not want to define an array and you have IsRequired validations. For this scenario, I could not find any light from MongoDB forums where they pointed out that was a bug that they needed to face out. The workaround that they suggest, it is to use the "ref" attribute that must link to the name of the schema after modelling in your MongoDB instance:

var City = connection.model('City', CitySchema);

And another important thing, that must not be forgotten, is when inserting, it is necessary to insert first the reference and then the root row, including the instance of the previous reference. As an example:

var city = new City({cityName: "Malaga"});
city.save(function(err, newCity) {
var country = new Country({
countryName: "Spain", 
cities: [ newCity ],
mainCity: newCity
});

country.save();
});

That is it, I hope this helps you.

No hay comentarios:

Publicar un comentario