I'm beginning with Mongoose and I want to know how to do this type of configuration:
A recipe has different ingredients.
I have my two models:
Ingredient and Recipe:
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var IngredientSchema = new Schema({ name: String }); module.exports = mongoose.model('Ingredient', IngredientSchema);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var RecipeSchema = new Schema({ name: String }); module.exports = mongoose.model('Recipe', RecipeSchema);
To model relationships between connected data, you can reference a document or embed it in another document as a sub document. Referencing a document does not create a “real” relationship between these two documents as does with a relational database. Referencing documents is also known as normalization.
MongoDB References. Typically, MongoDB doesn't work with the concept of foreign keys. However, relational databases can use foreign keys to visualize data from multiple collections simultaneously.
This is __v field that is only generated when a document(s) is inserted through mongoose. The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero.
The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.
Check Updated code below, in particular this part: {type: Schema.Types.ObjectId, ref: 'Ingredient'}
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var IngredientSchema = new Schema({ name: String }); module.exports = mongoose.model('Ingredient', IngredientSchema);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var RecipeSchema = new Schema({ name: String, ingredients:[ {type: Schema.Types.ObjectId, ref: 'Ingredient'} ] }); module.exports = mongoose.model('Recipe', RecipeSchema);
To Save:
var r = new Recipe(); r.name = 'Blah'; r.ingredients.push('mongo id of ingredient'); r.save();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With