Search code examples
node.jsmongodbmongoosemongoose-schema

Trying to split Mongoose models out into sud documents


I'm sure this is a syntax issue somewhere along the way. I've got a Mongoose model where part of it looks like this:

SMS_Data: {
        _id: false,
        SMS_User: [{
            Username: {
                type: String
            },
            Password: {
                type: String
            }
        }]
    }

This works fine, but I'm trying to split things out into subdocuments. So I've created a SMS_User.js model that looks like this:

const mongoose = require('mongoose');

const sms_user = mongoose.Schema({
    SMS_User: {
        Username: {
            type: String
        },
        Password: {
            type: String
        }
    }
})

module.exports = sms_user;

I require it into the main model using: const sms_user = require('./SMS_User');

And tried changing the main model to now read like this:

SMS_Data: {
        _id: false,
        SMS_User: [sms_user]
    }

But this doesn't work. Instead of selecting the user I expected, based on the Username and Password. But when I use this from my login controller:

const user = await my_model.findOne({ 'SMS_Data.SMS_User.Username': userId, 'SMS_Data.SMS_User.Password': userPw });

it just selects the first record in the collection, instead of the correct one when I use the un-nested version of the model. Which suggest to me that the nesting of the sub model is wrong.

Like I say this could be glaringly obvious, but I'm just not seeing where I'm going wrong.

Thanks in advance.


Solution

  • the way you have broken down the schema is wrong since you have added an extra level of nesting (i.e 'SMS_Data.SMS_User.SMS_User.Username' etc).

    You need to remove the SMS_User from sms_user schema

      const sms_user = mongoose.Schema({
        Username: {
          type: String
        },
        Password: {
          type: String
        }
      })
    
      const parentSchema = mongoose.Schema({
        //other fields
        SMS_Data: {
          _id: false,
          SMS_User: [sms_user]
        }
      })