문제

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?

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top