Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose virtual set function not called when value is object

I have a mongoose schema with a virtual of mixed type. For example:

var mongoose = require('mongoose') // version 3.3.1

var FooSchema = new mongoose.Schema( { x: Number } );

FooSchema.virtual('v').set( function(value){ 
  console.log("SETTING", value); 
});

var Foo = mongoose.model('Foo', FooSchema);

new Foo( { v:1 } );
new Foo( { v:[] } );
new Foo( { v:{} } );

When I run this code I get:

SETTING 1
SETTING []

As you'll notice it never shows "SETTING {}", any reason why this doesn't work?

Reference to issue on Github

like image 572
evanrs Avatar asked Oct 04 '12 22:10

evanrs


People also ask

What is virtuals 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 does findById return Mongoose?

findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .

Can I use $in in Mongoose?

For such cases, mongoose provides the $in operator. In this article, we will discuss how to use $in operator. We will use the $in method on the kennel collection. For performing HTTP endpoint testing, we will use the postman tool.

How do you use virtual populate?

For populating virtual, we have to specify three necessary options: ref: It contains the name of the model from which we want to populate the document. localField: It is any field of the current collection. foreignField: It is any field of the collection from which we want to populate the document.


1 Answers

This was an open issue in Mongoose that's been fixed in a recent commit by Aaron Heckmann.

like image 152
evanrs Avatar answered Oct 16 '22 19:10

evanrs