Does mongoose's “distinct” function support regex in a query?

▼魔方 西西 提交于 2019-12-12 01:12:05

问题


I have the following bit of js in a node/mongoose project. I'm working on an autocomplete form. It works just fine with a regular "find", but I want to do a "distinct" find instead.

So here's where I'm at so far. The problem I believe is in the way the query is formed. Can someone help with my syntax in the distinct line? Or is it just that mongoose's "distinct" doesn't support regex in an optional query?

var text.term = 'johnny';
var regex = new RegExp("^"+text.term);
// execute the search
Performance.collection.distinct({lc_actor: regex}, function(err, docs) {
    var names = [];
    for(var nam in docs) {
        // push the lc_actor to the array
    names.push(docs[nam].lc_actor);
    }
    // send back via callback function
    callback(null, names);
});

And here's what my super-verbose (-vvvvvvvvvvvvv) mongoose console is showing:

Tue Nov 29 13:34:30 [conn1] runQuery called mydb.$cmd { distinct: "performances", query: {}, key: { lc_actor: /^johnny/ } }
Tue Nov 29 13:34:30 [conn1] run command mydb.$cmd { distinct: "performances", query: {}, key: { lc_actor: /^johnny/ } }
Tue Nov 29 13:34:30 [conn1] command mydb.$cmd command: { distinct: "performances", query: {}, key: { lc_actor: /^johnny/ } } ntoreturn:1 reslen:140 526ms

Any ideas?


回答1:


Answering my own question. I did indeed have syntax errors in mongoose's distinct method. It accepts 3 params, I only had 2. The correct syntax with a regex (or any condition) is:

Performance.collection.distinct('lc_actor', {lc_actor: regex}, function(err, docs) {

From Mongoose docs for Model.distinct():

Model.distinct(field, conditions, callback);

http://mongoosejs.com/docs/finding-documents.html



来源:https://stackoverflow.com/questions/8315992/does-mongooses-distinct-function-support-regex-in-a-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!