Search code examples
node.jsmongodbmongoosemongoose-schemamongoose-populate

Populate in Mongoose not working


I am trying to perform associations by referencing method. There are 2 models: 1. User 2. Product

I have established one-to-one relationship of 1 user can have multiple products. User creation is successful Product creation is successful

Code Inputs

var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/product_demo_x9");

Product Schema

var productSchema = new mongoose.Schema({
  category : String,
  Brand: String
});
var Product = mongoose.model("product", productSchema);

User Schema

var userSchema = new mongoose.Schema({
email: String,
name: String,
products: [
  {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Product"
  }
]
});`
var User = mongoose.model("user", userSchema);

User Creation

User.create({
  email: "[email protected]",
  name: "Maddy"
},function(err,newUser){
    if(err){
       console.log(err);
    }
    else {
       console.log(newUser);
    }
});

Product Creation

Product.create({
    category: "Smartwatches",
    Brand: "Samsung and Google"
}, 
function(err,product){
    console.log(product);
    User.findOne({name : "Maddy"},function(err,foundUser){
        if(err) {
            console.log(err);
        }
        else {
            foundUser.products.push(product);
            foundUser.save(function(err,updatedUser){
                if(err){
                     console.log(err);
                }
                else {
                        console.log(updatedUser);
                    }
                });
            }
    });
});

Display of associated Data on the console

User.find({email: "[email protected]"}).
populate("products").
exec(function(err,user){
    if(err){
        console.log(err);
    }
    else {
        console.log(user);
    }
});

Code Outputs

User Creation (Success)

[{
  products: [],
  _id: 5a47acb0317d4e3c2081b8ce,
  email: '[email protected]',
  name: 'Maddy',
  __v: 0
}]

Product Creation and associating (Success)

{
  _id: 5a47acd53c771123b4018ff1,
  category: 'Smartwatches_2',
  Brand: 'Samsung and Google',
  __v: 0
}
{
  products: [ 5a47acd53c771123b4018ff1 ],
  _id: 5a47acb0317d4e3c2081b8ce,
  email: '[email protected]',
  name: 'Maddy',
  __v: 1
}

Display of embedded data using populate - Failure!!

{ MissingSchemaError: Schema hasn't been registered for model "products".
Use mongoose.model(name, schema)
    at new MissingSchemaError

Can anyone please explain me how to do it correctly? Thanks in Advance


Solution

  • Solved Did the following

    1. Downgraded my Mongoose version from 5.00x to 4.10.8 using the following command npm remove mongoose then npm install [email protected] --save

    2. Made the following change in app.js file

      var userSchema = new mongoose.Schema({
      email: String,
      name: String,
      products: [
        {
          type: mongoose.Schema.Types.ObjectId,
          ref: "product" //<---- changed 'Product' to 'product'
        }
      ]
      });`
      var User = mongoose.model("user", userSchema);
      

    Thanks to the Stack community for giving a try!