我正在嘗試接收用戶位置并將其存盤在資料庫中。此外,用戶可以選擇是否要保存他以前的所有位置。所以我創建了一個布爾變數historyEnable:true/false。因此,當historyEnable 為真時,我想推送到historicLocation[]UserSchema 中的陣列,如果它為假,我只想更新currentLocation[]UserSchema 中的陣列。
控制器/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
})
})
模型/User.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,
}
}
]
此外,不確定如何制作請求正文以使該功能正常作業。
請求正文
{
"phone": " 1234",
"historicEnable": true,
"loications": [
{
"location": {
"latitude": 25,
"longitude": 35
},
"status": "safe"
}
]
}
綜上所述,如果historyEnable為true,資料將被推送到historyLocation,如果為false,則更新currentLocation。
我該如何解決這個問題?
uj5u.com熱心網友回復:
您可以將更新與聚合管道一起使用。如果historicEnable僅在 db 級別上已知:
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"
}
])
看看它在操場上的例子是如何作業的
如果historicEnable從輸入中知道,您可以執行以下操作:
exports.addLocation = asyncHandler(async (req, res, next) => {
const {phone, location, status, historicEnable, createdAt} = req.body;
const locObj = {location, status, 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
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/486581.html
標籤:javascript 节点.js mongodb 猫鼬
上一篇:如何在按鍵上選擇輸入標簽
