Estoy tratando de recibir la ubicación del usuario y almacenarla en la base de datos. Además, el usuario puede elegir si quiere guardar todas sus ubicaciones anteriores o no. Así que he creado una variable booleana historicEnable: verdadero/falso. Entonces, cuando historicEnable es verdadero, quiero pasar a la matriz historicLocation[] en UserSchema y, si es falso, solo quiero actualizar la matriz currentLocation[] en UserSchema.
controladores/auth.js
exports.addLocation = asyncHandler(async (req, res, next) => { const {phone, location, status, historicEnable} = req.body; let theLocation; if (historicEnable== true){ theLocation = await User.findOneAndUpdate( { phone }, { $push:{ locationHistoric: location, statusHistoric: status }}, { new: true } ) } else if(historicEnable== false){ theLocation = await User.findOneAndUpdate( { phone }, { location, status }, { new: true } ) } res.status(200).json({ success: true, msg: "A location as been created", data: theLocation, locationHistory: locationHistory }) })modelos/Usuario.js
... currentLocation: [ { location: { latitude: {type:Number}, longitude: {type:Number}, }, status: { type: String }, createdAt: { type: Date, default: Date.now, } } ], historicLocation: [ { locationHistoric: { latitude: {type:Number}, longitude: {type:Number}, }, statusHistoric: { type: String }, createdAt: { type: Date, default: Date.now, } } ]Además, no estoy seguro de cómo hacer el cuerpo de la solicitud para que funcione la función.
req.cuerpo
{ "phone": "+1234", "historicEnable": true, "loications": [ { "location": { "latitude": 25, "longitude": 35 }, "status": "safe" } ] }En resumen, si historicEnable es verdadero, los datos se enviarán a ubicación histórica y, si es falso, se actualizará la ubicación actual.
¿Como puedo resolver esto?
Puede usar una actualización con una canalización de agregación. Si historicEnable solo se conoce en el nivel de base de datos:
db.collection.update( {phone: "+1234"}, [ {$addFields: { location: [{location: {latitude: 25, longitude: 35}, status: "safe"}] } }, { $set: { historicLocation: { $cond: [ {$eq: ["$historicEnable", true]}, {$concatArrays: ["$historicLocation", "$location"]}, "$historicLocation" ] }, currentLocation: { $cond: [ {$eq: ["$currentLocation", false]}, {$concatArrays: ["$currentLocation", "$location"]}, "$currentLocation" ] } } }, { $unset: "location" } ])Vea cómo funciona en el ejemplo del patio de recreo
Si se conoce historicEnable a partir de la entrada, puede hacer algo como:
exports.addLocation = asyncHandler(async (req, res, next) => { const phone = req.body.phone const historicEnable= req.body.historicEnable const locObj = req.body.location.locationHistoric[0]; locObj.createdAt = req.body.createdAt const updateQuery = historicEnable ? { $push:{ locationHistoric: locObj}} : { $push:{ currentLocation: locObj}}; const theLocation = await User.findOneAndUpdate( { phone }, updateQuery, { new: true } ) res.status(200).json({ success: true, msg: "A location as been created", data: theLocation, locationHistory: locationHistory }) })