Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.99k stars 3.85k forks source link

Mongoose create not adding reference field to collection #15031

Open OlammieAO opened 2 weeks ago

OlammieAO commented 2 weeks ago

Prerequisites

Mongoose version

8.7.3

Node.js version

22.5

MongoDB version

7

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

11

Issue

I'm working on a project and I created a model that reference another model(collection) using the _id of that other model in my current model. To my shock, when I create a new document, the document I created will be inserted into the collection successfully but MongoDB wouldn't add/display the referenced field in the MongoDB collection and this makes the populate() not to be working, infact I couldn't find the referenced field in the Customers collection but other fields records(fullname, phone, email) i created are there.

Here are my codes:

-------baseCustomer.model.js

const baseCustomersSchema = new mongoose.Schema(
 {   
    customerType: {
        type: String,
        required: true,
        unique: true,
        enum: ['Bronze', 'Gold', 'Plantinum'],        
    },   
    role: {
        type: String,
        required: true,
        enum: ['User','Moderator', 'Admin'],
        default: 'User',
        unique: true
    },       
 }, 
 {
  timestamps: true,
},
);

const BaseCustomer = mongoose.model('BaseCustomer', baseCustomersSchema);

module.exports = BaseCustomer;

-------customer.model.js

const customersSchema = mongoose.Schema(
  {

    baseCustomer_id:{
      type: { type: Schema.Types.ObjectId, ref: 'BaseCustomer'},      
    },
    fullname: {
        type: String,
        required: [true, 'First Name cannot be empty'],
        trim: true,
        minLength: [3, 'Full Name must at least 3 characters.'],
        maxLength: [80, 'Full Name is too large'],
        unique: true,
        index: true,        
      },      
    phone: {
        type: String,
        minLength: [11, 'Phon number must be 11 characters.'],
        maxLength: [11, 'Phon number must be 11 characters.'],
        unique: true,
        index: true,
      },              
    email: {
      type: String,
      validate: [validator.isEmail, 'Provide a valid email'],
      trim: true,
      lowercase: true,
      unique: true,
      required: [true, 'Email address is required'],
      unique: true,
      index: true,
    },

    }, 
{
  timestamps: true,
},

);

const Customer = mongoose.model('Customer', customersSchema);

module.exports = Customer;

------Controller user controller.

const Customer = require('../models/customer.model.js');

const { baseCustomer_id, fullname, phone, email } = req.body;

formRecord = {
    baseCustomer_id: baseCustomer_id,
    fullname: fullname,
    phone: phone,
    email: email,    
   };   

const appCustomer = await AppCustomer.create(formRecord);

  if(!appCustomer){
     res.status(400).json({
         status: 'Failed',
         message: 'Error adding customer',
     });
  }

res.status(200).json({
 status: 'success',
 message: 'Congratulations!!! Your account has been successfully created.'
});

****WHAT I EXPECTED

a) I expected to see the baseCustomer_id in the Customers collection after I created record but I found just only the fullname, phone, email in the collection without the baseCustomer_id field. So, with the current challenge I cannot use something like populate() to get the customerType and role fields from the baseCustomer collection because there is no baseCustomer_id field in the Customers collection in MongoDB.

I want to be able to count Customers based on their customerType e.g Total Number of Bronze Customer, Total Number of Gold Customer, and Total Number of Platinum Customer in just one query using either aggregate or populate from mongoose nodejs. Thank you for your assistance in advance.

vkarpov15 commented 6 days ago

Can you please confirm that baseCustomer_id is actually set in your req.body? That would be one explanation for why that field isn't showing up in MongoDB.

Also, can you please confirm what the difference is between AppCustomer model and Customer model?