[英]HOWTO: Produce mongoDB query string for the fields dynamically from a javascript app
[英]Query fields dynamically in MongoDB
假设模式为:
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.