mongo聚合函数不适用于套接字io

时间:2018-11-02 11:42:09

标签: mongodb express socket.io

嗨,我正在尝试在套接字io函数中运行MongoDB查询.findOne正常工作,但查找和聚合函数根本不工作。在此处输入代码

mongo.connect('mongodb://localhost:27017', function (err, client) {
    const db = client.db('dbName');

    const bookWalker = db.collection('bookwalkers');
    const walker = db.collection('walkers');


    io.sockets.on('connection', function (socket) {
        socket.on('enterRoom', function (data) {
            socket.room = data.room;
            socket.join(data.room);
            console.log("connected to room", data.room);

            bookWalker.find({"pendingWalk._id":
                   ObjectId("5bd994d2f395622e0b8f71af")},async function(err,resp)  {
                       console.log("dataf",resp);
                       io.sockets.in(data.room).emit('getStartTime', resp[0]);
             });
       });
 });

});

这是数据库中的示例数据

{
"_id" : ObjectId("5bd994d2f395622e0b8f71ad"),
"pendingWalk" : [ 
    {
        "walkPicture" : [],
        "status" : 0,
        "walkPath" : [],
        "_id" : ObjectId("5bd994d2f395622e0b8f71af"),
        "bookedDate" : ISODate("2018-10-31T13:30:56.581Z"),
        "bookedTime" : ""
    }
],
"userId" : ObjectId("5b6e932062bce05ae5647980"),
"book_dt" : ISODate("2018-10-31T11:41:06.230Z"),
"__v" : 0}

该查询在mongo shell内运行正常。

1 个答案:

答案 0 :(得分:0)

mongodb find()返回一个游标而不是数组。您必须调用toArray()函数。

    bookWalker.find({"pendingWalk._id":ObjectId("5bd994d2f395622e0b8f71af")}).toArray(function(err,resp){
     console.log(resp[0]);
});