简体   繁体   中英

Query fields dynamically in MongoDB

Let's say the schema is:

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

How would I query one of the rows at random? For example:

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

This code get's an error SyntaxError: Unexpected token +

try like

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);
});

This is not going to give you the expected results

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

To get a random number range in JavaScript, you should probably be doing something like this:

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

To use this in your code

var conditions = {};
conditions["row" + randomWithRange(1, 2)] = "sup";

Rows.find(conditions, function(err, result){ ... });

You can't create a JavaScript object by building property names on the fly using the shortcut syntax, they must be literals (strings or numbers):

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

You can do this instead:

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

However, a more simple Mongoose way to express the query would be to use 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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM