在 db.collection.findOne( { parm : value } 中传递变量
Passing variable in db.collection.findOne( { parm : value }
我正在尝试创建一种方法,该方法将根据参数和类似值从集合中获取记录。
其中 parm 例如 该架构中的 _id 字段。
getRecord('_id', '1234567876543')
getRecord(parm, value){
db.collection.findOne( { parm : value } , function(err, item) {
if (err) {
console.error(err);
}else if (item === null ) {
console.error('record does not exist');
}else {
Record = JSON.stringify(item);
}
});
}
发生的事情是这段代码试图从不存在的 table 中获取列参数,每次返回的记录都不存在。
如何在 findOne 查询中传递参数值?
如果要在对象的关键部分传递变量,可以使用方括号传递。在你的情况下,这样做:
db.collection.findOne( { [parm] : value } , function(err, item) {
或者,您可以将它分配给一个对象,例如:
var query = {};
query[parm] = value;
db.collection.findOne( query , function(err, item) {...})
我正在尝试创建一种方法,该方法将根据参数和类似值从集合中获取记录。
其中 parm 例如 该架构中的 _id 字段。
getRecord('_id', '1234567876543')
getRecord(parm, value){
db.collection.findOne( { parm : value } , function(err, item) {
if (err) {
console.error(err);
}else if (item === null ) {
console.error('record does not exist');
}else {
Record = JSON.stringify(item);
}
});
}
发生的事情是这段代码试图从不存在的 table 中获取列参数,每次返回的记录都不存在。
如何在 findOne 查询中传递参数值?
如果要在对象的关键部分传递变量,可以使用方括号传递。在你的情况下,这样做:
db.collection.findOne( { [parm] : value } , function(err, item) {
或者,您可以将它分配给一个对象,例如:
var query = {};
query[parm] = value;
db.collection.findOne( query , function(err, item) {...})