I’ve built 2 very simple schemas below called Farms and Products. Farms has a field which is an array of product references as a Farm can have many products in my design. I’ve been able to use ‘FarmModel’ & ‘ProductModel’ as a gateway to carry out CRUD operations successfully in my JS e.g.
ProductModel.findById(
const theFarm = new FarmModel(req.body.myFarm)
But I run into an issue when I try to use populate:
farmModel.findOne({ name: 'Full Belly Farms' })
.populate('products')
.then(farmFound => console.log(farmFound))
ERROR: Schema hasn’t been registered for model “ProductModel” .
What am I doing wrong?
const FarmSchema = new mongoose.Schema({
name: { type: String, required: [true, "Farm must have a name"] },
city: { type: String },
email: { type: String, required: [true, "Email address is reqd"] },
products: [{ type: mongoose.Schema.Types.ObjectId, ref: 'ProductModel' }]
})
const FarmModel = mongoose.model('Farm', FarmSchema)
ProductSchema = new mongoose.Schema({
name: { type: String, required: [true, "Product name must be included"] },
price: { type: Number, required: true, min: 1 },
category: { type: String, enum: ['fruit', 'vegetables', 'dairy'], lowercase: true }
})
const ProductModel = mongoose.model('Product', ProductSchema);
The other question I have is typically when you define a model for a schema you use the following format:
const FarmModel = mongoose.model('Farm', FarmSchema)
FarmModel is the model
FarmSchema is the schema
'Farm' …so what is this called? I know this is used when naming the collection. It’s made plural and the first letter is made lowercase so the collection will be called ‘farms’. I couldn’t find an explanation for this in the documentation.