mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Mongoose not returning Define schema structure

Open Enado95 opened this issue 7 years ago • 4 comments

I have an express API using an already populated mongoDB and have defined the schema like so:

const accountHolderSchema= new mongoose.Schema({
  pid: {Type: Number},
  accountNumber: {type: String},
  relationshipType: {type: String},
  firstName: {type: String},
  middleName: {type: String},
  lastName: {type: String}
});

const accountsSchema = new mongoose.Schema({
  accountNumber: String,
  accountType: String,
  accountHolder: [accountHolderSchema]
});

 
const productDetailSchema = new mongoose.Schema({
  pid: Number,
  accounts: [accountsSchema]
});

I have literally copied and paste all the properties and from the database so i know they match so i know that's out of the picture

The RESPONSE I get is this:

{
"pid": 2697143,
    "accounts": [
        {
            "accountHolders": [
                {
                    "pid": 13209741,
                    "accountNumber": "403716000062",
                    "relationshipType": "BENEFICIARY",
                    "firstName": "Maria",
                    "middleName": "Delores",
                    "lastName": "Jackson"
                }
             ]
            "accountNumber": "12345",
            "accountType": "RSA",
        }
     ]
}

BUT what the response I WANT to get is this:

{
"pid": 2697143,
    "accounts": [
        {
            "accountNumber": "12345",
            "accountType": "RSA",
            "accountHolders": [
                {
                    "pid": 13209741,
                    "accountNumber": "403716000062",
                    "relationshipType": "BENEFICIARY",
                    "firstName": "Maria",
                    "middleName": "Delores",
                    "lastName": "Jackson"
                }
             ]
        }
     ]
}

I want the accountNumber and accountNumber to come before accountHolders field.

I'm not sure if its the way how i define a nested array inside of another nested array that's throwing of the structure. If I don't the define accountHolderSchema the structure is returned fine. Any ideas?

Enado95 avatar Apr 07 '19 01:04 Enado95

Hey @Enado95, accountNumber and accountType are keys in an Object, not values in an Array.

The contents of an Object do not represent an ordered group of things -- they are only things you can look up by their key. We have to assume that the javascript interpreter could reorder them at any time, even though it gives us some convenience functions to iterate over the set of all of them.

If you need to pull keys out of an object in a specific order, it is best to have a separate array somewhere that encodes the order you care about, and pull keys by iterating over it, something like this:

const pullOrder = ['accountNumber', 'accountType', 'accountHolders'];
for (const key of pullOrder) {
    console.log(account[key]);
}

This also separates the of the order of presentation from the order of storage, which means you would not have to alter your schema definition if some part of your application's needs with regard to key-order changed in the future. You would only have to update your pullOrder array. Likewise, if you had to change your schema in the future to add new fields, it would not impact your application code.

Hopefully that gives some ideas to help work around this limitation of the language/framework :)

wcarss avatar Apr 11 '19 16:04 wcarss

I understand. But it would be way easier if the response returned matched what you defined by default. It works with simple nested array, just not one that looks like mine. I just want to know if it is a genuine issue or I'm doing something wrong

Enado95 avatar Apr 11 '19 17:04 Enado95

@Enado95 the issue comes down to the fact that arrays have an implicit default value of []. Mongoose sets the default array value before setting the data from the database, so accountHolders becomes the first key. Add default: void 0 to your array fields as shown below, and you'll get your desired key order:

const assert = require('assert');
const mongoose = require('mongoose');
mongoose.set('debug', true);

const GITHUB_ISSUE = `gh7692`;
const connectionString = `mongodb://localhost:27017/${ GITHUB_ISSUE }`;
const { Schema } = mongoose;

run().then(() => console.log('done')).catch(error => console.error(error.stack));

async function run() {
  await mongoose.connect(connectionString);
  await mongoose.connection.dropDatabase();

  const accountHolderSchema= new mongoose.Schema({
    pid: {Type: Number},
    accountNumber: {type: String},
    relationshipType: {type: String},
    firstName: {type: String},
    middleName: {type: String},
    lastName: {type: String}
  });

  const accountsSchema = new mongoose.Schema({
    accountNumber: String,
    accountType: String,
    accountHolders: { type: [accountHolderSchema], default: void 0 } // Avoid setting empty array by default
  });

  const productDetailSchema = new mongoose.Schema({
    pid: Number,
    accounts: { type: [accountsSchema], default: void 0 } // And here as well
  });

  const Model = mongoose.model('Product', productDetailSchema);

  await Model.create({
"pid": 2697143,
    "accounts": [
        {
            "accountNumber": "12345",
            "accountType": "RSA",
            "accountHolders": [
                {
                    "pid": 13209741,
                    "accountNumber": "403716000062",
                    "relationshipType": "BENEFICIARY",
                    "firstName": "Maria",
                    "middleName": "Delores",
                    "lastName": "Jackson"
                }
             ]
        }
     ]
});

  console.log(await Model.findOne());
}

vkarpov15 avatar Apr 21 '19 18:04 vkarpov15

This works thanks a lot!

Enado95 avatar Apr 23 '19 16:04 Enado95