簡體   English   中英

將用戶位置保存到mongodb,nodejs服務器

[英]save user location to mongodb, nodejs server

當我嘗試找到用戶的位置並將其保存到我登錄的用戶的位置字段中的mongodb時,我已經了解了問題。 使用護照進行身份驗證。 連接到nodejs並將數據保存到mongodb,一切正常。 我不明白該怎么做才能在mongo中將實時位置保存在用戶的位置字段中。 這是我的第一個js / nodejs / databse應用程序,我知道這並不難,但是我找不到應該怎么做。

我無法向您展示我已經嘗試過的內容,因為我唯一嘗試過的只是了解原理。 這是我的用戶架構

const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true },
  date: {
    type: Date,
    default: Date.now },
  loc: {
    type: { type: String },
    coordinates: [Number]
  }
});
const User = mongoose.model('User', UserSchema);
module.exports = User;

我希望在mongodb用戶集合中的loc字段中,當我登錄時能看到我的實時坐標。

如果我正確理解了該問題,則希望獲取登錄到您的應用程序的用戶的位置。

一種可能的方法是在身份驗證過程中請求獲得位置的權限。

為此,您可以使用GEOLOCATION API並先驗證瀏覽器是否支持它,然后再向用戶請求坐標。

然后,如果用戶同意,則您將位置放入第二個POST請求中,並與第一個POST請求一起發送,該請求用於獲取auth令牌。 為此,您將需要創建一個新的API端點(此示例以express編寫):

app.post("/users/:id", async (req, res) {
   try {
      const user = await User.findById(req.params.id);
      user.loc = req.body.LOCATION_DATA_THAT_YOU_SENT_FROM_THE_FRONTEND;
      user.save();
      } catch(err) {
      console.error(err);
   }

順便說一句,如果您希望loc成為一個對象,那么您應該創建另一個Mongoose模式並從UserSchema引用它:

const LocationSchema = new mongoose.Schema({
   smthing: String,
   coords: Number    
})

// in UserSchema
...
loc: {
   type: LocationSchema
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM