Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying on a virtual property in mongoose

Tags:

I have a virtual property in my mongoose schema, I would like to know if I can query my documents using this property.

var PersonSchema = new Schema({   number: {type: Number, required: true},   name: {type: Date, required: true} });  PersonSchema.virtual('capitalCaseName').get(function () {   return this.name.toUpperCase(); }); ... Person.find({"capitalCaseName": "DANIEL"}).exec(); ... 
like image 581
danielrvt Avatar asked Dec 17 '14 22:12

danielrvt


People also ask

What is virtual property in Mongoose?

In Mongoose, a virtual is a property that is not stored in MongoDB. Virtuals are typically used for computed properties on documents.

What are virtual methods Mongoose?

Virtuals are document properties that do not persist or get stored in the MongoDB database, they only exist logically and are not written to the document's collection.

What is virtual populate in Mongoose?

Populating Virtuals: In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

What is __ V 0 in Mongoose?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ). If you don't want to use this version key you can use the versionKey: false as mongoose.


1 Answers

No, you can't. Mongoose virtual properties only exist in the Mongoose model representation of documents, not in MongoDB itself where the query is performed.

Any field you need to query against must be defined in the schema as a non-virtual field and persisted to the database.

like image 125
JohnnyHK Avatar answered Oct 09 '22 09:10

JohnnyHK