Javascript 如何将用户数据自动发送到mongo DB

Javascript 如何将用户数据自动发送到mongo DB,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,我使用socket.io广播地理位置(lat、lng),并在每次用户连接到应用程序时在地图上设置新的标记图标。如果日本用户连接,socket.io将向我发送他的位置,他也将接收我的位置。问题是,我不希望用户接收(并将我的位置发送给)距离较远的用户的位置,但只能在预定义的半径范围内(例如:20公里) mongo DB中的空间搜索似乎适合识别位于同一区域的用户并将其分配给groupId。相同groupId的用户将被分配一个他们将侦听的公共socket.io通道 为了让我的梦想成真,我正试图用mong

我使用socket.io广播地理位置(lat、lng),并在每次用户连接到应用程序时在地图上设置新的标记图标。如果日本用户连接,socket.io将向我发送他的位置,他也将接收我的位置。问题是,我不希望用户接收(并将我的位置发送给)距离较远的用户的位置,但只能在预定义的半径范围内(例如:20公里)

mongo DB中的空间搜索似乎适合识别位于同一区域的用户并将其分配给groupId。相同groupId的用户将被分配一个他们将侦听的公共socket.io通道

为了让我的梦想成真,我正试图用mongoose将用户信息推送到MongoDB中。问题是mongoose在服务器上运行,而数据在客户端

我已经定义了一个schema.js来构造数据库,但我对如何设置将客户机数据与mongoose链接的路由有点迷茫?我知道mongoose和client都必须返回适当的JSON对象进行通信,并且可以使用
model.save()
存储数据。很抱歉这个天真的问题,但如果您能在这一点上提供帮助,我们将不胜感激。多谢各位

编辑:

    // generate unique user id
    var userId = Math.random().toString(16).substring(2,15);

    // code here
    onLocationfound = function(e){
        userMarker.setLatLng(e.latlng);
        map.setView(userMarker.getLatLng(),map.getZoom()); 
        latitude = (e.latlng[0]||( Math.round(e.latlng.lat*1000)/1000));
        longitude = (e.latlng[1]||( Math.round(e.latlng.lng*1000)/1000));

    // send data to database (executed once)
    sentData = {id: userId, coords: [{lat: latitude, lng: longitude}]}
    socket.emit('send2DB', sentData);
mongoose.connect('mongodb://localhost/test');

var mongoose = require('mongoose')
    , Schema = mongoose.Schema
    , ObjectId = Schema.ObjectId;

// create schema
var userInformation = new Schema({
    username: { type: String, required: true, trim: true },
    email: { type: String, required: true, trim: true },
    role: { type: String, required: true, trim: true },
    date: {type: Date, default: Date.now},
    userId: String,
    longitude: Number,
    latitude: Number,
    coords: [Number, Number]
});

// export retrieve my model

var MyModel = mongoose.model('ModelName', userInformation);
var instance = new MyModel();

// code here

io.sockets.on('connection', function (socket) {

// code here

// Store user data to DB then query spatial info //
socket.on('send2DB', function (data) {

    console.log('Position is', data);
    instance.push(
        {userId: 'data.id'},
        {latitude: 'data.lat'}
        );
    instance.save(function (err) {
      if (!err) console.log('Success!')
      else console.log('Error');
    });

});
我最终使用socket.io通过
send2DB
功能将用户数据传递到服务器,但我遇到了以下错误:

Object { _id: 50fc08aebb97d3201d000001,
coords; [],
date: Sun Jan 20 2013 16:18:34 GMT+0100 (Paris, Madrid) } has no methode 'push'`
数组
coords
似乎有问题,但我不明白为什么它也会返回日期! 代码如下:

application.js:

    // generate unique user id
    var userId = Math.random().toString(16).substring(2,15);

    // code here
    onLocationfound = function(e){
        userMarker.setLatLng(e.latlng);
        map.setView(userMarker.getLatLng(),map.getZoom()); 
        latitude = (e.latlng[0]||( Math.round(e.latlng.lat*1000)/1000));
        longitude = (e.latlng[1]||( Math.round(e.latlng.lng*1000)/1000));

    // send data to database (executed once)
    sentData = {id: userId, coords: [{lat: latitude, lng: longitude}]}
    socket.emit('send2DB', sentData);
mongoose.connect('mongodb://localhost/test');

var mongoose = require('mongoose')
    , Schema = mongoose.Schema
    , ObjectId = Schema.ObjectId;

// create schema
var userInformation = new Schema({
    username: { type: String, required: true, trim: true },
    email: { type: String, required: true, trim: true },
    role: { type: String, required: true, trim: true },
    date: {type: Date, default: Date.now},
    userId: String,
    longitude: Number,
    latitude: Number,
    coords: [Number, Number]
});

// export retrieve my model

var MyModel = mongoose.model('ModelName', userInformation);
var instance = new MyModel();

// code here

io.sockets.on('connection', function (socket) {

// code here

// Store user data to DB then query spatial info //
socket.on('send2DB', function (data) {

    console.log('Position is', data);
    instance.push(
        {userId: 'data.id'},
        {latitude: 'data.lat'}
        );
    instance.save(function (err) {
      if (!err) console.log('Success!')
      else console.log('Error');
    });

});
server.js:

    // generate unique user id
    var userId = Math.random().toString(16).substring(2,15);

    // code here
    onLocationfound = function(e){
        userMarker.setLatLng(e.latlng);
        map.setView(userMarker.getLatLng(),map.getZoom()); 
        latitude = (e.latlng[0]||( Math.round(e.latlng.lat*1000)/1000));
        longitude = (e.latlng[1]||( Math.round(e.latlng.lng*1000)/1000));

    // send data to database (executed once)
    sentData = {id: userId, coords: [{lat: latitude, lng: longitude}]}
    socket.emit('send2DB', sentData);
mongoose.connect('mongodb://localhost/test');

var mongoose = require('mongoose')
    , Schema = mongoose.Schema
    , ObjectId = Schema.ObjectId;

// create schema
var userInformation = new Schema({
    username: { type: String, required: true, trim: true },
    email: { type: String, required: true, trim: true },
    role: { type: String, required: true, trim: true },
    date: {type: Date, default: Date.now},
    userId: String,
    longitude: Number,
    latitude: Number,
    coords: [Number, Number]
});

// export retrieve my model

var MyModel = mongoose.model('ModelName', userInformation);
var instance = new MyModel();

// code here

io.sockets.on('connection', function (socket) {

// code here

// Store user data to DB then query spatial info //
socket.on('send2DB', function (data) {

    console.log('Position is', data);
    instance.push(
        {userId: 'data.id'},
        {latitude: 'data.lat'}
        );
    instance.save(function (err) {
      if (!err) console.log('Success!')
      else console.log('Error');
    });

});

我认为你大体上走在正确的道路上。以下是几个容易注意到的问题:

  • push
    方法从何而来?(您没有任何数组)
  • 当从客户机接收到新数据时,您不想在MyModel的新实例上设置属性吗
  • 我认为当套接字检索send2DB数据时,您应该创建一个新的MyModel。然后,只需设置属性
  • 另外,您不想将
    用户id
    设置为带引号的字符串
    'data.id'
    ,是吗?您不是只想要值吗,就像
    userId:data.id
    ?(您可能需要套接字
    数据
    对象中的值)
  • 在猫鼬身上可以找到最基本的东西


    最终,您可能希望为API函数添加一些安全性之类的内容,而不仅仅是信任User.id是否有效以及位置。

    您需要在连接中为socket.io编写一些代码,以便使用会话或其他令牌跟踪特定用户。然后,当新数据进来时,在服务器上为具有地理数据的特定事件编写处理程序,以更新位置。您只需编写一个API层,供客户端应用程序调用。客户端不会(也不应该)直接调用数据库。我已经用新代码和结果更新了我的帖子。为了简化,我尝试在找到用户的位置后存储数据。然后我会查询一些空间信息,以便识别他周围的用户。你能看看我的错误吗?谢谢你,谢谢你。1.你说得对。
    push
    在这里不合适。2.这正是我想要的。3.我现在明白了。4.那是我的错误。正如您所建议的,一旦调用了
    send2DB
    ,我就创建我的模型<代码>if(!err)console.log('Success!')else console.log(实例)显示发生错误且实例未定义。我是否要在Express和socket.io会话中添加您提到的安全性?tx@floflo是的,我想用Express&socket.io添加安全性。在
    函数(err,instance)
    中添加实例回调的目的是什么?因为没有它它就不会报告错误,比如:
    instance.save(函数(err){if(err){console.log(err);}else-console.log('Information added to the database');})如果您使用的是闭包,则不需要。但是,这是mongoose文档显示的内容,因此为了完整起见,我将其包括在内。我使用
    索引:{unique:true}
    设置了userId,以避免在用户位置发生变化时重复用户。我无法使用
    .update
    来管理这种情况,
    $exists:true
    .save
    重新运行错误。不管怎样,我会试着检查代码。谢谢你的帮助。