我环顾四周并尝试了各种文档,以便能够让 MongoDB 中的 $where
子句为我工作,但它就是行不通。
这是我的对象:
var UserProfiles = [{
userProfileID: "3f8c553c-3633-4fe9-a007-4346a783450c",
firstName: 'Austin',
lastName: 'Hunter',
email: 'ahunter8....com',
token: '',
platform: '',
password: 'admin',
companyProfileID: "86660a5b-7f61-4238-889d-1cc3087947b9",
authentication: ''
}....
在 UserProfiles 对象中插入了几个“配置文件”。这只是第一个。
这是我插入到集合中的:
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
} else {
console.log("We are connected");
}
var collection = db.collection('UserProfile');
for (var i = 0; i < UserProfiles.length; i++) {
collection.insert(UserProfiles[i], function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
}
db.close();
});
现在我正在尝试在我的收藏中搜索传入的电子邮件和 companyProfileID。如果它们都匹配,则返回该配置文件。我认为 $where
子句是最好的,但我无法让它工作。
这是我试图找到的():
function getUserProfile(passInEmail, companyID, callback) {
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
} else {
console.log("We are connected");
}
var collection = db.collection('UserProfile');
collection.find({$where: "this.email == passInEmail"}, function(err, result) {
if (err) {
console.log(err);
callback(err);
} else if (result.length) {
console.log(result);
callback(result);
} else {
callback(err);
console.log("No document found");
}
});
db.close();
});
}
我正在尝试搜索集合,如果对象 email 与传入的 email 匹配并且对象 companyProfileID 与传入的 companyID 匹配,则成功。
最佳答案
你的情况下的 $where
子句不是最好的。
你应该简单地做:
//userIdParam ad emailParam are two variables
collection.find({userProfileID: userIdParam, email: emailParam})
.toArray(function(err, result) {
if (err) {
console.log(err);
callback(err);
} else if (result.length) {
console.log(result);
callback(result);
} else {
callback(err);
console.log("No document found");
}
});
查看文档 here
关于javascript - MongoDB $where 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40094649/