sac Dahal
sac Dahal

Reputation: 1241

mongodb schema.createIndex is not a function

So I am trying to create an index in my messageSchema

    var messageSchema = new Schema({
    senderName : String,
    content : String,
    reply : String,
    date: { type: Date, default: Date.now() },
    room : { type: Schema.Types.ObjectId }
});

// this is how to tried to create the index

 messageSchema.createIndex({content : "text"}, function(err, data){
     console.log(err);
     console.log(data);
    });

//Also tried

  messageSchema.createIndex({content : "text"}); 

//tried this too

 messageSchema.createIndex({"content" : "text"});

The error I keep on getting is

TypeError: messageSchema.createIndex is not a function

Can anyone help me with this.

Upvotes: 3

Views: 12106

Answers (3)

Emir Mamashov
Emir Mamashov

Reputation: 1170

from mongoose:

var messageSchema = new Schema({
    senderName : String,
    content : { type: String, index: true },
    reply : String,
    date: { type: Date, default: Date.now() },
    room : { type: Schema.Types.ObjectId }
});
 messageSchema.index({content: 'text'});

Upvotes: 4

Derlin
Derlin

Reputation: 9891

It seems you are using mongoose. Under the hood,

Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

In the mongo shell, collection.createIndex() works, but in mongoose you need to use mySchema.index(). Mongoose will do the work.

See here for more information: http://mongoosejs.com/docs/guide.html.

Upvotes: 13

Mario Trucco
Mario Trucco

Reputation: 2011

The method you are looking for is called index, not createIndex

Upvotes: 0

Related Questions