gpt4 book ai didi

node.js - 当 mongodb 发生变化时更新客户端中的位置

转载 作者:太空宇宙 更新时间:2023-11-04 03:07:45 26 4
gpt4 key购买 nike

我正在制作一个 Android 应用程序并使用 Express 作为后端。这是我的送货员架构:

var DeliveryBoySchema = new Schema({

name: String,
college: {type:String},
password: {type: String, required: true, select: false},
lat:{type: String},
long:{type:String}

});

当送货员改变位置时,它会在 mongodb 中更新。因此,正在查看该送货员的用户(即客户)正在跟踪他的位置。我找到了两种方法来做到这一点:

1。客户端每5秒调用一次api并获取送货员的当前位置。

2。我发现了另一种有趣的方法来做到这一点,即使用套接字。

我不太清楚它的功能。当数据库发生更改并且用户看到当前位置时,我遇到如何更新客户端的问题。

最佳答案

根据 OP 的要求,仅使用 mongoosenodeJSsocket 进行一些编码。实际实现不必完全相同,但以下内容应该给出如何继续进行并填补缺失空白的总体思路。为了方便起见,我将使用 ES6 功能。

nodeJS版本4.2.2,socket.io 1.3.5,mongoose版本4.1.2,express 4.13.3

  1. 创建套接字 - 服务器端

//the following is probably your app.js
import express from 'express'
...
var app = express();
var server = http.createServer(app);
...

var socketio = require('socket.io')(server, {
path: '/socket.io-path, //modify this as per your needs
});
//now register created socket object
require('./components/socket')(socketio);

...
//start the server

//the following is components/socket/index.js

function onConnect(socket){
//register listeners on mongo schema changes
require('../../models/deliveryBoy.socket').register(socket);
}

module.exports = function(socketio){
socketio.on('connection', function(socket) {
socket.address = socket.request.connection.remoteAddress +
':' + socket.request.connection.remotePort;
//address, e.g. 127.0.0.1:52243

socket.connectedAt = new Date();
socket.log = function(...data) {
console.log(`SocketIO ${socket.address}`, ...data);
};
// Call onDisconnect.
socket.on('disconnect', function() {
socket.log('Disconnected: ');
//do something when user disconnects
});

// Call onConnect.
onConnect(socket);
socket.log('New connection: ');
});
};

  • 在 mongoose 架构定义上附加一个钩子(Hook)
  • //this is to be stored at ./models/deliveryBoy.model 

    'use strict';

    var mongoose = require('bluebird').promisifyAll(require('mongoose'));
    var Schema = mongoose.Schema;

    var DeliveryBoySchema = new Schema({
    name: String,
    college: {type:String},
    password: {type: String, required: true, select: false},
    lat:{type: String},
    long:{type:String}
    });

    //attach a hook to be triggered every time you modify the document
    //has to be inserted before the mongoose model is created !!!
    //with !!!ATTENTION!!! update method using $set
    //for example DeliveryBoy.update({_id:'blah'}, {$set: {long: 1, lat: 0}});
    DeliveryBoySchema.post('update', function(){
    var update = this._update;
    if (update.$set && (update.$set.lat || update.$set.long)){
    try{
    var updatedObjectId = this._conditions._id; //will serve as a room
    var newLoc = {
    lat: update.$set.lat,
    long: update.$set.long
    }
    //now emit the event using nodejs event emitter

    require('../../components/app.events').emit('updateLoc', {roomId: updatedObjectId, newLoc: newLoc});
    }
    }
    });

    module.exports = mongoose.model('DeliveryBoy', DeliveryBoySchema);

  • DeliveryBoy 的套接字监听器
  • //this is the component which implement socket specifically for delivery boy model
    //it is called (register method) from general components/socket module

    exports.register = function(socket){
    AppEvents.on('updateLoc', function(socket){
    return function(info){
    socket.to(info.roomId).emit('newLocation', info.newLoc);
    }
    });
    }

  • 现在您只需根据送货员 ID 从客户端连接到房间,并使用来自客户端的消息并相应地更新您的 View
  • 还有一件事,这就是如何通过 REST API 更新数据库

    app.put('/update/:gameId', function(req, res){
    DeliveryBoy.update({_id: req.params.gameId}, {$set: req.body}, function(err){
    res.send(200); //of course this needs to be handled properly, but i am too tired after typing all these
    //you owe me couple beers dude
    });
    });

    P.S 代码有点乱,不过你应该可以做出相应的改进。如果有任何问题请告诉我。但基本概念应该清楚

    关于node.js - 当 mongodb 发生变化时更新客户端中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34636154/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com