简单来说,根本不需要设置它。问题可能会因为你的mongoose schema而变得更加复杂。从MongoDB的角度来看,如果属性不存在,它并不关心,并会在索引中忽略它。
实际上是“mongoose”在你不想创建结构时创造了这些东西,所以只需“告诉它”如果你没有提供任何数据,则不要包含该结构:
location: {
type: { type: String },
coordinates: { type: [], default: undefined }
}
只要将
coordinates
数组设置为
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"
的属性中没有无效的数据可以被索引。