Node.js 由于ID类型,无法对本机MongoDB应用find()方法
我有一个函数需要得到结果 当我给1个as\u id过滤器时,一切都正常Node.js 由于ID类型,无法对本机MongoDB应用find()方法,node.js,mongodb,sails.js,mongodb-query,node-mongodb-native,Node.js,Mongodb,Sails.js,Mongodb Query,Node Mongodb Native,我有一个函数需要得到结果 当我给1个as\u id过滤器时,一切都正常 collectionPersonnel .find({ '_id' : 1 }) .toArray(function (err, personnel) { console.log(personnel); }); 如果我为实例用户[0]['personals\u id']]提供另一种过滤方式,即存储1,那么我只得到[]结果 collectionPersonnel .find({
collectionPersonnel
.find({ '_id' : 1 })
.toArray(function (err, personnel) {
console.log(personnel);
});
如果我为实例用户[0]['personals\u id']]提供另一种过滤方式,即存储1,那么我只得到[]结果
collectionPersonnel
.find({ '_id' : user[0]['personnel_id'] })
.toArray(function (err, personnel) {
console.log(personnel);
});
然后我尝试了另一种方法。但它不起作用,因为我使用了字符串(用户[0]['personals\u id']),而不是ObjectID
var ObjectID = require('mongodb').ObjectID;
var personnelPK_Hex = (user[0]['personnel_id']).toHexString();
var personnelPK = ObjectID.createFromHexString(personnelPK_Hex);
我该怎么办
编辑
我所有的代码都在下面
module.exports = {
show: function(req, res) {
User.native(function(err, collectionUser) {
if(err) {
console.log("There is no exist a User by current_id");
};
collectionUser
.find({'_id' : req.param('id')})
.toArray(function (err, user) {
Personnel.native(function(err, collectionPersonnel) {
if(err) {
// handle error getting mongo collection
console.log("There is no exist a Personel by current _id");
};
if(!collectionPersonnel) {
console.log("There is no exist a Personel by current _id");
};
// var ObjectID = require('mongodb').ObjectID;
// var personnelPK_Hex = (user[0]['personnel_id']).toHexString();
// var personnelPK = ObjectID.createFromHexString(personnelPK_Hex);
collectionPersonnel
.find({ '_id' : user[0].personnel_id })
.toArray(function (err, personnel) {
console.log(personnel);
});
});
});
});
}
};
控制台的输出是;
[]
解决了的
就像阿普西勒说的。我错误地给了集合一个数字id。
我已经确定了id值,一切正常
collectionPersonnel
.find({ '_id' : 1 })
.toArray(function (err, personnel) {
console.log(personnel);
});
谢谢大家…尝试使用like用户[0]。个人\u id而不是用户[0]['personal\u id']请提供您的架构设计,以便更好地了解您到底缺少了什么 我这样试过了
collectionPersonnel
.find({ '_id' : user[0].personnel_id })
.toArray(function (err, personnel) {
console.log(personnel);
});
user[0]['personals\u id']
可能是字符串。对于Mongo,“1”
与1
不同,这就是为什么文字数字1
有效,而变量(包含字符串)无效的原因
相反,请尝试使用一元加号将字符串转换为数字:
+user[0]['personal\u id']
谢谢你的建议,David。我试过你的建议,但不管用。同时,当我将用户[0].personal\u id或用户[0]['personal\u id']写入console.log时,控制台会正确地输出1。(我不知道如何提供模式设计)我一直在尝试嵌套查询。首先查询“用户”集合,然后使用返回第一次查询结果的“User.personal\u id”查询人员集合。实际上,这是一个嵌套查询。我正在编辑我的问题。再次感谢你,没错!你是对的!我刚才解决了这个问题。无论如何,谢谢…@apsillers-继续吧,把你的解决方案作为答案发布,这样OP可以给你打分