Home > Software engineering >  MongoDB auto pushes arrays into data schemas
MongoDB auto pushes arrays into data schemas

Time:09-18

I'm being in a case in which I don't know why or what causes it. I can't find any info on this weird problem. So I'm gonna ask here.

//mongoDB data schema
const dataSchema = mongoose.Schema({
    userID: String,
    userStocks: Array,
    stockMarket: Array,
});
module.exports = mongoose.model('Data', dataSchema);

The problem then arrives when creating a new collection in the database:

var regUser = new Data({
   
});
console.log(regUser); return;

The console.log(regUser) returns both the stockMarket array and userStock array as empty arrays.

Why is this? And how do I prevent it?

It works fine with Number and String type. But with Array type it seems to auto insert it for some reason.

I've tried with delete regUser.stockMarket but it does nothing despite returning true when run. I've also tried removing them with an aggregate using $unset and $merge but still nothing.

So does anyone have any idea what could be causing this weird case? And how would I fix it?

-----------EDIT-----------
Based on the answer from @HuyPham I found out the problem was that I didn't correctly declare it as in array in the schema constructor. The correct way of doing it was:

const dataSchema = mongoose.Schema({
   userID: String,
   userstocks: {
       type: Array,
       default: undefined
   },
   stockMarket: {
       type: Array,
       default: undefined
   }
});

CodePudding user response:

You have defined Array type in mongoose.Schema in the wrong way. Take a look at Arrays in mongoose docs. In case you receive empty array for userStocks and stockMarket maybe it's take Array instance as default value.

In the correct way you found above, make an adjustment from type: Array to type:[] to prevent unpredictable issues when using JavaScript Array instance to set type.

const dataSchema = mongoose.Schema({
   userID: String,
   userstocks: {
       type: [],
       default: undefined
   },
   stockMarket: {
       type: [],
       default: undefined
   }
});
  • Related