【问题标题】:Mongoose find value from other collection猫鼬从其他收藏中找到价值
【发布时间】:2019-01-01 08:53:39
【问题描述】:

这是我的模型:

var RaceSchema = new mongoose.Schema({
    name: {
        type: String
    },
    owner:{
        type: mongoose.Schema.ObjectId, ref:"user"
    }
});
var UserSchema = new mongoose.Schema({
    username: { 
        type: String
    }
});

这是我的收藏示例:

//Races
{
    "_id": {
        "$oid": "5b5740c54befec2594ce4cb0"
    },
    "name": "Race1"
    "owner": {
        "$oid": "5b34f870e1eef640f8cb43e4"
    }
}
//User
{
    "_id": {
        "$oid": "5b34f870e1eef640f8cb43e4"
    },
    "username":"admin"
}

我想查找所有者与字段 username 匹配的种族。我是说: "我想查找所有者为 admin 的种族"

我正在尝试这个:

Race.find().populate('users', {username: 'admin'}).exec(function (err, races) {
    ....
}

但结果总是一样的,搜索给了我所有的种族。

编辑 1

SQL 语句是:

Select * FROM Races,Users WHERE owner=user._id AND user.username='admin' 

或者类似的东西

【问题讨论】:

  • 如何使用find 属性并指定您真正想要查找的内容?

标签: javascript node.js mongoose populate


【解决方案1】:

我终于做到了。解决方案:

这是我的代码:

var query=[{
        "$lookup": {
            "from": "users",
            "localField": "owner",
            "foreignField": "_id",
            "as": "user"
        }
    },{
        "$unwind": "$user"
    },{
        "$match": {
            "$and": [{
                "user.username": username
            }]
        }
    }];
Race.aggregate(query, function (err, races){
    ....
}

【讨论】:

    【解决方案2】:

    要从两个不同的集合中获取数据,您需要使用 aggregate 函数和 $lookup (see the docs)

    你可以在 mongoose (see this question) 中找到它的等价物

    【讨论】:

    • 我不想从两个不同的集合中获取数据。 SQL 语句是:Select * FROM Races,Users WHERE owner=user._id AND user.username='admin' 或类似的东西
    【解决方案3】:

    一旦你得到所有的比赛使用数组方法过滤器

    示例

    let adminRaces = races.filter(x=>x.owner['$oid'] === admin._id['$oid'])
    

    这里是参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      相关资源
      最近更新 更多