当前位置 : 主页 > 网页制作 > Nodejs >

node.js – 如果array是变量,则[array]中的nodejs mongodb $无效

来源:互联网 收集:自由互联 发布时间:2021-06-16
这对我来说很奇怪.如果把数组onlyIds放在我的db的聚合查询中,我得不到任何结果.但是,如果我把第4行打印的onlyIds的内容看起来像: ["52e953942a13df5be22cf792","52e953942a13df5be22cf793","52e953942a13
这对我来说很奇怪.如果把数组onlyIds放在我的db的聚合查询中,我得不到任何结果.但是,如果我把第4行打印的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或字符串.对于其他任何人,请确保db中的变量与您尝试与之匹配的变量类型相同.在我的情况下,两者都应该是字符串,但“onlyIds”中的一个是ObjectIds.

尝试以下代码来修改循环:

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(函数(错误,…(因为您使用了聚合框架,因此不在您的情况下).如果您不使用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);
              });
            });
    });
});
网友评论