在MongoDB中动态查询字段

bzu*_*ick -1 javascript json mongoose mongodb node.js

让我们说架构是:

var Rows = mongoose.model('Rows', {   
    row1: String,
    row2: String
});
Run Code Online (Sandbox Code Playgroud)

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

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

这段代码出错了 SyntaxError: Unexpected token +

mit*_*esh 6

试试吧

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);
});
Run Code Online (Sandbox Code Playgroud)