Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Index on a field in nested document

I have a small schema

var PostSchema = new mongoose.Schema({
  title: String,
  link: String,
  author: {type:String,required:true},
  upvotes: {type: Number, default: 0},
  nesteddoc : {
      field1: String
  }
});

//This is broken - index on field1
PostSchema.index({nesteddoc.field1:1},{unique:true});

Is it possible to have an index on nested field by specifying in Mongoose schema and not running a MongoDB query to ensure the index ?

like image 598
Prateek Narendra Avatar asked Feb 21 '17 13:02

Prateek Narendra


People also ask

What is the __ V field in Mongoose?

In Mongoose the “_v” field is the versionKey is a property set on each document when first created by Mongoose. This is a document inserted through the mongo shell in a collection and this key-value contains the internal revision of the document.24-Jun-2021.

What can Mongoose specify in a schema?

A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

What is ref in schema Mongoose?

The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.

What is schema path in Mongoose?

You can think of a Mongoose schema as the configuration object for a Mongoose model. A SchemaType is then a configuration object for an individual property. A SchemaType says what type a given path should have, whether it has any getters/setters, and what values are valid for that path.


1 Answers

Use quotes around "nesteddoc.field1" to evaluate the nested field :

PostSchema.index({ "nesteddoc.field1": 1 }, { unique: true });

Furthermore, mongoose will call ensureIndex internally, from mongoose doc :

When your application starts up, Mongoose automatically calls ensureIndex for each defined index in your schema. Mongoose will call ensureIndex for each index sequentially, and emit an 'index' event on the model when all the ensureIndex calls succeeded or when there was an error. While nice for development, it is recommended this behavior be disabled in production since index creation can cause a significant performance impact. Disable the behavior by setting the autoIndex option of your schema to false, or globally on the connection by setting the option config.autoIndex to false.

You can also define index in schema :

var PostSchema = new mongoose.Schema({
    title: String,
    link: String,
    author: { type: String, required: true },
    upvotes: { type: Number, default: 0 },
    nesteddoc: {
        field1: { type: String, unique: true, index: true },
    }
});
like image 174
Bertrand Martel Avatar answered Oct 22 '22 18:10

Bertrand Martel