简体   繁体   中英

MongoError: query selector must be an object

I am trying to dynamically build a query, I can build it and copy and paste it straight into the console and it works.

It seems that the query is not recognised as an object which is where I am stuck:(

Is there a way that I can convert the query string into an obbject that mongodb can recognise?

This is used in nodejs 6.10

var string = "tag1,tag2".split(",").map(function (a) { return new RegExp('^' + a) }).join(", ");

var query = '{ "optionsSearch": { "$all": [ ' + string + ' ] } }';

// this is my desired query below, if I copy and paste this straight into the query it works? 

console.log(query);  ///<- { "optionsSearch": { "$all": [ /^tag1/, /^tag2/ ] } } 

mongodb.MongoClient.connect('mongodb://*******:*****@aws-eu-west-1-portal#####', function (err, db) {

console.log("Connected to mongo");

var minidealers = db.collection('collection1');

minidealers.find(query) //<- FAILS MongoError: query selector must be an object
    .limit(100)
    .toArray(function (err, items) {
        console.log(items);
    });
});

Well you can use JSON.parse for that:

minidealers.find(JSON.parse(query))

But really you should have just been working with JavaScript objects in the first place.

var query = { 
   "optionsSearch": { 
    "$all": "tag1,tag2".split(",").map(function (a) { return new RegExp('^' + a) })  
    }
};

// And then
minidealerts.find(query)

So there was no need in either of the places where you hacked the object into a string to even do that. It makes much more sense to work with the native objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM