json数组的Mongoose查询

时间:2014-04-01 13:04:21

标签: json node.js mongodb mongoose

我是node.js的新手,并且使用mongoose和node.js。

架构:

var userSchema = new mongoose.Schema({
username: String,
password: String,
phone_no : String,
email: String,
name:String,
dob: {type: Date, "default": Date.now},
city:String,
locality:{lattitude:Number,longitude:Number},
sports: [String]
});

样本条目:

"userId": 10,
    "username": "shu",
    "name": "shubham goyal",
    "password": "ahu",
    "phone_no": "919357701457",
    "email": "shubham2892@gmail.com",
    "city": "delhi",
    "_id": {
        "$oid": "5331dbc243bb59f80a7ed60b"
    },
    "sports": [
        "cricket,football"
    ],
    "dob": {
        "$date": "2014-03-25T19:40:50.886Z"
    },
    "__v": 0
}

我想要的查询:

models.user.find({'sports' : sports_selected},function(err,users) {
        if(err) {
            console.log("Cannot fetch sports with requested username" + req.user.username);
            console.log(err);
        }if(!users){
            console.log("cannot find specified username" + req.user.username);
        }else{
            console.log(users.username);
            //sport = player.sports;
            //sport = ['cricket','football','basketball'];

            }
        });

我在users.username中未定义。我希望返回选择了特定运动的所有用户说'板球'。我搜索了很多但是找不到任何东西。

1 个答案:

答案 0 :(得分:0)

您的示例条目看起来格式不正确。体育参赛不应该是这样的:

"sports": [
        "cricket,football"
]

你应该保留这样的体育数据:

"sports": [
        "cricket","football"
]

如果你用相同的弦提供板球和足球,mongo不能将这两者区分为不同的运动。

此外,用户应该是一个数组,因此您需要遍历数组。假设您有一个运动被选为板球用户,那么您可以打印用户[0] .username