I find myself in a puzzling situation without knowing the cause. Despite my efforts, I cannot seem to find any information on this strange issue. Therefore, I have turned to seek help here.
//mongoDB data schema
const dataSchema = mongoose.Schema({
userID: String,
userStocks: Array,
stockMarket: Array,
});
module.exports = mongoose.model('Data', dataSchema);
The dilemma arises when attempting to create a new collection in the database:
var regUser = new Data({
});
console.log(regUser); return;
Upon running console.log(regUser)
, both the stockMarket
array and userStock
array appear as empty arrays.
Why is this happening? And how can it be prevented?
It behaves properly with Number
and String
types. However, for some reason, when using the Array
type, it automatically inserts them.
I have attempted removing them with delete regUser.stockMarket
, which seemingly does nothing despite returning true
when executed. Additionally, I tried eliminating them through an aggregate using $unset
and $merge
without success.
Does anyone have insight into what might be causing this peculiar scenario? And how could it be resolved?
-----------EDIT-----------
Following @HuyPham's response, I discovered that the issue stemmed from not correctly declaring it as an array in the schema constructor. The proper approach was:
const dataSchema = mongoose.Schema({
userID: String,
userstocks: {
type: Array,
default: undefined
},
stockMarket: {
type: Array,
default: undefined
}
});