草庐IT

node.js - 如果数组是变量,nodejs mongodb $in [array] 不工作

coder 2023-10-28 原文

这对我来说很奇怪。如果将数组 onlyIds 放入我的数据库的聚合查询中,我将得不到任何结果。但是,如果我把从第 5 行打印出来的 onlyIds 的内容放在一起,如下所示:

["52e953942a13df5be22cf792","52e953942a13df5be22cf793","52e953942a13df5be22cf797"...]

然后就可以了。但如果我使用变量则不会。

这个函数:

var onlyIds = [];
for (var i = 0; i < users.length; i++) {
    onlyIds.push(users[i]._id);
}
console.log("ids: " + JSON.stringify(onlyIds));      <---------- not empty

db.collection('posts', function(err, collection) {
    collection.aggregate([
        {$match: {user_id: {$in: onlyIds}}},   <------- not working
        {$match: {created:{$gte: 0}}},
        {$sort:{"created": -1}},
        {$skip: req.body.skip},
        {$limit: req.body.limit}
    ], 

    function(err, posts) {
        var errorNo, content, message;
        if (err) {
            errorNo = resSend.errorDB;
            message = JSON.stringify(err);
        } else {
            errorNo = resSend.errorNo;
            content = posts;
            message = "";
-->         console.log(JSON.stringify(posts));
        }
        resSend.sendResponse(res,  resSend.errorNo, content, message);
    });
});

简而言之,为什么这样做有效:

{$match: {user_id: {$in: ["52e953942a13df5be22cf792","52e953942a13df5be22cf793","52e953942a13df5be22cf797"...]}}}

这不是:

{$match: {user_id: {$in: onlyIds}}}

而行不通的那一行,在另一个函数中运行得很好。有什么想法或启示吗?

编辑: 切换为查找并使用以下答案,如下所示:

collection.find({'user_id': {$in: onlyIdsX}}).toArray(function(err, posts)

也不行。

回答:

正如下面所选答案所示,当您搜索的变量是 ObjectId 或字符串时。对于其他任何人,请确保数据库中的变量与您尝试匹配的变量类型相同。在我的例子中,两者都应该是字符串,但“onlyIds”中的一个是 ObjectId。

最佳答案

尝试使用以下代码修改循环:

var ids = ["52e953942a13df5be22cf792","52e953942a13df5be22cf793","52e953942a13df5be22cf797"];
var obj_ids = [];
for (var i = 0; i < users.length; i++) {
    obj_ids.push(new ObjectID(users[i]._id.toString()));    
    var obj_ids.push(users[i]._id);    // <== This will not work if your DB has _id : ObjectID("xyz") [i.e. you are not overiding defaults]
}

并且您应该在代码中包含 var ObjectID = require('mongodb').ObjectID;
您应该使用 .toArray(function(err,.. (在您的情况下不适用,因为您使用了聚合框架)。如果您不使用 findOne()(有关这方面的更多信息,请访问 link)


以下是发现问题(在评论中)和工作代码的示例:

var mongo = require('mongodb'),
    Server = mongo.Server,
    Db = mongo.Db,
    ObjectID = require('mongodb').ObjectID;
var BSON = require('mongodb').BSONPure;
var server = new Server('localhost', 27017, {
    auto_reconnect: true
}); 
var MongoClient = require('mongodb').MongoClient

//let id = your _id, smth like '6dg27sh2sdhsdhs72hsdfs2sfs'...
var users = ["52e953942a13df5be22cf792","52cbd028e9f43a090ca0c1af","52e953942a13df5be22cf797"];
var obj_ids = [];
for (var i = 0; i < users.length; i++) {
    obj_ids.push(new ObjectID(users[i].toString()));    
    //obj_ids.push(users[i]._id);    // <== This will not work if your DB has _id : ObjectID("xyz") [i.e. you are not overiding defaults]
}

MongoClient.connect('mongodb://127.0.0.1:27017/YourDBName', function(err, db) {
    console.log('err'  +  err);
    db.collection('posts', function(error, collection) {
            //collection.find({_id:{$in: users}}),function(err, docs) { //This will not work
            collection.find({_id:{$in: obj_ids}}).toArray(function(err, docs) {
              console.log("Printing docs from Array. count " + docs.length);
              docs.forEach(function(doc) {
                console.log("Doc from Array ");
                console.dir(doc);
              });
            });
    });
});

关于node.js - 如果数组是变量,nodejs mongodb $in [array] 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22907451/

有关node.js - 如果数组是变量,nodejs mongodb $in [array] 不工作的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby - 在 Ruby 中实现 `call_user_func_array` - 2

    我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)

  4. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  5. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  6. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  7. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  8. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  9. ruby-on-rails - Rails 3 I18 : translation missing: da. datetime.distance_in_words.about_x_hours - 2

    我看到这个错误:translationmissing:da.datetime.distance_in_words.about_x_hours我的语言环境文件:http://pastie.org/2944890我的看法:我已将其添加到我的application.rb中:config.i18n.load_path+=Dir[Rails.root.join('my','locales','*.{rb,yml}').to_s]config.i18n.default_locale=:da如果我删除I18配置,帮助程序会处理英语。更新:我在config/enviorments/devolpment

  10. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

随机推荐