Mongoose通过操纵数据表现怪异



我已经挠头四个小时了。正如你所看到的,我刚刚用Mongoose查询了MongoDB,我得到了结果,但data似乎被操纵了!我不确定是buffer overflow还是underflow或其他什么。这是我的简化nodejs代码:

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));
});
});

这是控制台日志:

(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 ]

products对象与products keysproducts values不匹配。

注意:实际上有一个文档的'shirt', 'glove', 'mitten', 'glasses'作为其products键,但所有这些键都有值。

问题出在Schema上。我忘记了将sunGlasses, normalGlasses, smokeGlasses, sportGlasses添加到模式的products字段中。我修改了我的模式:

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

现在products可以是任何对象。

最新更新