How do I include a virtual field in a JSON response
const ItemSchema = mongoose.Schema({
name: String,
time: { type: Date, default: Date.now }
});
ItemSchema.virtual('timeleft').get(function() {
this.timeleft = 24
var currentTime = moment();
var timeStored = moment.utc(this.time).local().format();
this.timeleft -= currentTime.diff(timeStored, 'h');
});
API call
app.get('/getAllItems', function(req, res, next) {
Item.find({}, function(err, items) {
res.json(items);
});
});
So technically the response won't include virtual timeleft field. Am I missing something?
[
{
name: "nike",
time: "21/2/22"
},
{
name: "adidas",
time: "21/2/22"
},
]
// use Schema like this
const ItemSchema = new Schema({
name: String,
time: { type: Date, default: Date.now }
}, {
toObject: { virtuals: true },
toJSON: { virtuals: true }
});
ItemSchema.virtual('timeleft').get(function() {
// this.timeleft = 24
var currentTime = moment();
var timeStored = moment.utc(this.time).local().format();
console.log(" ====== 000 ======== ", currentTime.diff(timeStored, 'h'))
return this.timeleft = currentTime.diff(timeStored, 'h');
});
const Item = mongoose.model('Item', ItemSchema);
new Item({
name: 'Axl'
}).save((err, result) => {
console.log("=== err ", err, "=== result ", result)
});
Item.find({}, function(err, items) {
console.log("=========", items)
});
According to Mongoose docs Mongoose virtuals are not stored in MongoDB, which means you can't query based on Mongoose virtuals.
// Will **not** find any results, because `domain` is not stored in
// MongoDB.
const doc = await User.findOne({ domain: 'gmail.com' });
doc; // undefined
If you want to query by a computed property, you should set the property using a custom setter or pre save middleware.
Modify your schema as shown below:
const ItemSchema = mongoose.Schema({
name: String,
time: { type: Date, default: Date.now },
toObject: { virtuals: true }, // <-- These properties will configure
toJSON: { virtuals: true } // model to include virtuals
});
Modify your API call as follows:
app.get('/getAllItems', function(req, res, next) {
Item.find({}, function(err, items) {
res.json(items.toObject()); // <-- use .toObject() or .toJSON()
});
});