简单地说,根本不要设置它。您的猫鼬模式可能会使问题更加复杂。从 MongoDB 的角度来看,它并不关心该属性是否根本不存在,并将随后在索引中忽略它。
它是“猫鼬”,它会在您不想要的时候实际创建东西,所以如果您不提供任何数据,只需“告诉它”不要包含结构:
location: {
type: { type: String },
coordinates: { type: [], default: undefined }
}
只要将coordinates数组设置为default到undefined值,那么mongoose在持久化到数据库时就不会尝试将“空数组”添加到文档中,这会导致索引的问题。
作为一个完整的演示:
const { Schema } = mongoose = require('mongoose');
const uri = 'mongodb://localhost/test';
mongoose.Promise = global.Promise;
mongoose.set('debug', true);
const geoSchema = new Schema({
name: String,
location: {
type: { type: String },
coordinates: { type: [], default: undefined }
}
});
const GeoTest = mongoose.model('GeoTest', geoSchema);
const log = data => console.log(JSON.stringify(data, undefined, 2));
(async function() {
try {
const conn = await mongoose.connect(uri);
await Promise.all(Object.entries(conn.models).map(([k,m]) => m.remove()));
await GeoTest.insertMany([
{
"name": "Sydney",
"location": {
"type": "Point",
"coordinates": [
151.21170043945312,
-33.86414397991936
]
}
},
{ "name": "Nowhere" }
]);
let results = await GeoTest.find();
log(results);
} catch(e) {
console.error(e)
} finally {
process.exit()
}
})()
其中显示存储的文档为:
[
{
"location": {
"type": "Point",
"coordinates": [
151.21170043945312,
-33.86414397991936
]
},
"_id": "5af8e6c17c91d648feb26cc4",
"name": "Sydney",
"__v": 0
},
{
"_id": "5af8e6c17c91d648feb26cc5",
"name": "Nowhere",
"__v": 0
}
]
因此,如果您实际上不提供任何location 数据,那么那里就什么都没有。这让 MongoDB 很高兴,因为在要为 "2d" 或 "2dsphere" 编制索引的属性中没有无效数据。