Synopsis
I want to rename the ‘address’ field to ‘location’ in my Mongoose schema. The location field only stores address data, such as street, city, postcode, etc. The locationGeo field, on the other hand, contains the geospatial data in the form of a GeoJSON Point for coordinates.
Error
After renaming the ‘address’ field to ‘location’, I am encountering the following error:
MongoServerError: Can't extract geo keys: { <user_data> } unknown GeoJSON type: { street: "Wiejska", city: "Warszawa", postcode: "00-480", streetNumber: "2G", apartmentNumber: null, voivodeship: "mazowieckie" }
Code
userModel:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
firstName: { type: String, default: null },
lastName: { type: String, default: null },
nickname: { type: String, unique: true },
password: { type: String, required: true },
email: { type: String, required: true, unique: true },
phone: { type: String, default: null },
location: {
street: { type: String },
city: { type: String },
postcode: { type: String },
streetNumber: { type: String },
apartmentNumber: { type: Number },
voivodeship: { type: String },
},
locationGeo: {
type: { type: String, default: 'Point' },
coordinates: {
type: [Number],
default: [0, 0],
},
},
});
userSchema.index({ locationGeo: '2dsphere' });
userSchema.index({
phone: 1
}, {
unique: true,
partialFilterExpression: { phone: { $type: "string" } }
});
module.exports = mongoose.model("User", userSchema);
Function which updates userModel:
module.exports.updateBasicInfo = async (req, res) => {
const user = res.entity;
const session = await mongoose.startSession();
session.startTransaction();
console.log(req.body)
// {
// firstName: '',
// lastName: '',
// location: {
// street: 'Wiejska',
// city: 'Warszawa',
// postcode: '00-480',
// streetNumber: '45',
// apartmentNumber: '',
// point: { lat: 52.2275274, lng: 21.0237868 }
// }
// }
const { location: newLocation } = req.body;
const locationGeo = {
type: "Point",
coordinates: [newLocation.point.lng, newLocation.point.lat],
};
delete newLocation.point; //don't store coordinates in location
const updateData = {
$set: {
location: newLocation || {},
locationGeo: locationGeo,
}
};
try {
await user.updateOne(updateData, { session });
await session.commitTransaction();
return res.json(user);
} catch (error) {
await session.abortTransaction();
console.error(error);
return res.status(400).json({ message: error.message || "Update failed." });
} finally {
await session.endSession();
}
};
I’ve tried:
- Verifying that locationGeo is being updated correctly with valid GeoJSON data.
- Attempting to update only the location field without updating the locationGeo field at all.
Can anyone explain why this error occurs after renaming the field and how to resolve it while keeping ‘location’ as the field name for the address?