在MongoDB中动态查询字段

Query fields dynamically in MongoDB

本文关键字:查询 字段 动态 MongoDB      更新时间:2023-09-26

假设模式是:

var Rows = mongoose.model('Rows', {   
    row1: String,
    row2: String
});

如何随机查询其中一行?例如:

var rand = Math.floor(Math.rand() * 2);
Rows.find({ "row" + rand: "sup" }, function (err, result) {
    if (err) {
        console.log(err);
    }
    console.log(result);
});

此代码是一个错误SyntaxError: Unexpected token +

像一样尝试

var rand = Math.floor(Math.rand() * 2);
var objFind = {};
objFind["row" + rand] = "sup";
Rows.find(objFind, function (err, result) {
    if (err) {
        console.log(err);
    }
    console.log(result);
});

这不会给您带来预期的结果

Math.floor(Math.random() * 2)

要在JavaScript中获得随机数范围,您可能应该执行以下操作:

var randomWithRange = function (min, max) {
    return Math.random() * (max - min) + min;
};

要在您的代码中使用此

var conditions = {};
conditions["row" + randomWithRange(1, 2)] = "sup";
Rows.find(conditions, function(err, result){ ... });

您不能通过使用快捷方式语法动态构建属性名称来创建JavaScript对象,它们必须是文本(字符串或数字):

var x = { "row1" : "sup" };

你可以这样做:

var x = {};
var rowNum = 1;
x["row" + 1] = "sup";

然而,Mongoose表达查询的一种更简单的方法是使用where(docs):

var rand = Math.floor(Math.rand() * 2) + 1;
Rows.where("row" + rand, "sup").exec(function (err, result) {
    if (err) {
        console.log(err);
    }
    console.log(result);
});