i am using nodejs express and mangodb, when a user signup i want to get the live location of the use geospatial code . this is the error i get when i run my code .
MongoServerError: Can't extract geo keys: { _id: ObjectId('675af307f2a7bcc8878ea08b'), citizenName: "citizen44", citizenEmail: "[email protected]", hashedPwd: "$2b$10$wvGKMqASwi/cQryjRbGSluHJlbnrnZX6YKmxu2CoiqcSRBAsVILD2", location: ObjectId('675af307f2a7bcc8878ea088'), status: "student", role: { Basic: 1997 }, createdAt: new Date(1734013703839), updatedAt: new Date(1734013703839), __v: 0 } geo element must be an array or object: location: ObjectId('675af307f2a7bcc8878ea088')
this the code // Register a new user
const registerNewUser = async (req, res) => {
// Validate request data
const result = validationResult(req);
if (!result.isEmpty()) {
return res.status(400).send({ errors: result.array() });
}
const data = matchedData(req);
const { citizenName, citizenEmail, passCode, confirmPwd, latitude, longitude, status } = data;
try {
// Create location object
const location = new Location({
location: {
type: 'Point',
coordinates: [longitude, latitude]
}
});
// Save the location to the database
const savedLocation = await location.save();
// Check for duplicate citizen name
const duplicate = await Citizen.findOne({ citizenName: citizenName }).exec();
if (duplicate) {
return res.status(409).json({ message: 'Citizen name already exists' });
}
// Hash the password
const hashedPwd = await bcrypt.hash(passCode, 10);
// Create citizen document
const citizen = new Citizen({
citizenName,
citizenEmail,
hashedPwd,
location: savedLocation._id, // Ensure this matches the schema
status,
role
});
// Save the citizen to the database
await citizen.save();
return res.status(201).send(citizen);
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Content was not uploaded', error: err.message });
}
};
this is the model of the location
// models/location.js
const mongoose = require('mongoose');
const locationSchema = new mongoose.Schema({
// name: { type: String, required: true },
location: {
type: { type: String, enum: ['Point'], required: true },
coordinates: { type: [Number], required: true } // [longitude, latitude]
}
});
// Create a geospatial index
locationSchema.index({ location: '2dsphere' });
const Location = mongoose.model('Location', locationSchema);
module.exports = Location;
i want to get the user live location and able to save it to the database get the last insertedID and insert it inside the citizen collection.