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 ?
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.
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.
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.
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.
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 },
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With