【问题标题】:.aggregate(...).toArray is not a function.aggregate(...).toArray 不是函数
【发布时间】:2019-02-01 07:55:23
【问题描述】:

这是我遇到错误的代码。 我尝试了多种方法,但总是遇到同样的错误。 TypeError: _user10.default.aggregate(...).toArray 不是函数 我搜索了其他答案,但它们是 mongodb 而不是 mongoose ex db.collection('users').aggregate 任何帮助将不胜感激

import User from './user.model';
import socket from './../../CHATtest/web/socket.js';



getUserInfo({userId,socketId = false}){
    let queryProjection = null;
    if(socketId){
        queryProjection = {
            "socketId" : true
        }
    } else {
        queryProjection = {
            "username" : true,
            "online" : true,
            '_id': false,
            'id': '$_id'
        }
    }
    return new Promise( async (resolve, reject) => {
        try {
    //const result = await User.aggregate([{
    //await User.aggregate([{
    User.aggregate([{
    //DB.collection('users').aggregate([{
                $match:  {
                    _id : userId
                }
            },{
                $project : queryProjection
            }
  ]).toArray( (err, result) => {
                if( err ){
                    reject(err);
                }
                socketId ? resolve(result[0]['socketId']) : resolve(result);
            });
        } catch (error) {
            reject(error);
        }
    });
},

【问题讨论】:

标签: node.js mongodb mongoose socket.io


【解决方案1】:

根据 Mongoose 文档,调用 Model.aggregate() 会返回一个 Aggregate 对象 (https://mongoosejs.com/docs/api.html#model_Model.aggregate)。它没有 toArray() 方法,这就是您收到错误的原因。

Aggregate 对象是可链接的,您需要通过调用 exec() 来结束链接。这将返回一个承诺 (https://mongoosejs.com/docs/api.html#aggregate_Aggregate)

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 2020-09-12
    • 2021-09-30
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    相关资源
    最近更新 更多