Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mongoose create not adding reference field to collection #15031

Open
1 task done
OlammieAO opened this issue Nov 12, 2024 · 1 comment
Open
1 task done

Mongoose create not adding reference field to collection #15031

OlammieAO opened this issue Nov 12, 2024 · 1 comment
Labels
help This issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessary needs clarification This issue doesn't have enough information to be actionable. Close after 14 days of inactivity

Comments

@OlammieAO
Copy link

OlammieAO commented Nov 12, 2024

Prerequisites

  • I have written a descriptive issue title

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.

@OlammieAO OlammieAO added help This issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessary help wanted labels Nov 12, 2024
@vkarpov15
Copy link
Collaborator

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?

@vkarpov15 vkarpov15 added needs clarification This issue doesn't have enough information to be actionable. Close after 14 days of inactivity and removed help wanted labels Nov 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help This issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessary needs clarification This issue doesn't have enough information to be actionable. Close after 14 days of inactivity
Projects
None yet
Development

No branches or pull requests

2 participants