Mongoose acting weird by manipulating data

Viewed 67

I'm scratching my head for almost four hours now. As you see, I've just queried the MongoDB with Mongoose and I got the result, but it seems somehow data get manipulated! I'm not sure if it's buffer overflow or underflow or something else. here is my simplified nodejs code:

let mongoose = require("mongoose");


mongoose.connect("mongodb://localhost:27017/shop", {}).then(() => {
  let schema = new mongoose.Schema({
    categoryId: {
      type: Number,
      required: true,
    },
    products: {
      shirt: {
        type: String,
        required: true,
      },
      glove: {
        type: String,
        required: true,
      },
      mitten: {
        type: String,
        required: true,
      },
      glasses: {
        type: String,
        required: true,
      },
    },
  });
  let Model = mongoose.model("Model", schema, "services_products");
  Model.findOne({ categoryId: { $exists: false } }).then((data) => {
    console.log("data: ", data);
    console.log("products: ", typeof data.products, data.products);
    console.log("products keys: ", Object.keys(data.products));
    console.log("products values: ", Object.values(data.products));
  });
});

and here is the console logs:

  (node:15151) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:15151) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
  data:  {
  products: {
    sunGlasess: 'MAIN_STORE',
      normalGlasses: 'MAIN_STORE',
      smokeGlasses: 'MAIN_STORE',
      sportGlasses: 'MAIN_STORE'
  },
  _id: 5fe1d3ad223ac40b32038415
}
products:  object {
  sunGlasess: 'MAIN_STORE',
    normalGlasses: 'MAIN_STORE',
    smokeGlasses: 'MAIN_STORE',
    sportGlasses: 'MAIN_STORE'
}
products keys:  [ '$init', 'shirt', 'glove', 'mitten', 'glasses' ]
products values:  [ true, undefined, undefined, undefined, undefined ]

The products object doesn't match with products keys and products values.

Note: There is actually a document with 'shirt', 'glove', 'mitten', 'glasses' as its products keys, but all of them has value.

1 Answers

The problem was the Schema. I had forgotten to add sunGlasses, normalGlasses, smokeGlasses, sportGlasses to the products field of the schema. I modified my schema:

let schema = new mongoose.Schema({
    categoryId: {
      type: Number,
      required: true,
    },
    products: mongoose.Schema.Types.Mixed
  });

Now products can be any object.

Related