arrays - 如果数组包含 id mongoose 则获取数组

标签 arrays node.js mongodb mongoose mongoose-schema

这是一个棘手的问题。我以为我可以使用$in,但查询后,它不是我要找的地方。

这是我的架构

var gameSchema = new mongoose.Schema({
    state: {
        type: String,
        default: "invited"
    },
    finished: {
        type: Boolean,
        default: false
    },
    players: {
        type: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'users'
        }],
        required: true,
    },
    scores: [scoreSchema],
    chat : [chatSchema]
});

我尝试发出的请求如下,我发送一个用户 ID,如果玩家数组包含此 Id,则返回数组中的另一个 id(该数组的长度始终为 2)。

上下文是你可以查找你以前玩过的对手。

这就是我所拥有的,但“玩家”应该是一个数组,而且我想返回的不是游戏,所以

exports.getFriends = function(id, cb){
    gameSchema.find({ id: { "$in": "players"} }, function(err, games){
        if(err){
            return cb(err, null);
        }
        else{
            return cb(null, games);
        }
    });
};

最佳答案

你能试试这个吗?

exports.getFriends = function(id, cb){
    gameSchema.find({ players: id }, function(err, games) {
        if (err) {
            return cb(err);
        }
        const players = games.map(game => game.players);
        const mergedPlayers = [].concat.apply([], players);
        const mappedPlayers = mergedPlayers.map(String); // convert ObjectIds to strings for comparisons.
        const idString = String(id);
        const filteredPlayers = mappedPlayers.filter(player => player !== idString);
        const uniquePlayers = filteredPlayers.filter((player, index, arr) => arr.indexOf(player) === index);
        return cb(null, uniquePlayers);
    });
};

我假设您需要一个唯一玩家 ID 数组,这些玩家 ID 不是您传入的玩家 ID。我将变量分开,而不是链接所有数组方法,以提高可读性。

关于arrays - 如果数组包含 id mongoose 则获取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39110906/

相关文章:

java - 蒙戈 : How to count aggregation groups via Java's MongoTemplate

C++ 跳过一维数组中的元素

创建优化的总和减少

javascript - 在 typescript Jest 上下文中, Node 配置配置是 `undefined` 吗?

node.js - 向 sequelize 中的所有表添加一列

java - 将数据从 PostgreSQL 迁移到 MongoDB

c# - 将二维数组从 VB6 编码到 .NET

c++ - 如何判断指针是否是指向数组的指针?

node.js - Firebase Cloud Firestore 触发器 context.auth 始终为 null

mongodb - 从 Go 访问 MongoDB