如何使用Mongoose查询虚拟字段?

时间:2017-01-14 07:56:25

标签: node.js mongodb mongoose

如何查询虚拟字段,以便它在JSON响应中

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调用

app.get('/getAllItems', function(req, res, next) {
   Item.find({}, function(err, items) {
     res.json(items);
   });
});

因此从技术上讲,响应将不包括虚拟时间字段。我错过了什么吗?

[
 {
   name: "nike",
   time: "21/2/22"

  },

  {
   name: "adidas",
   time: "21/2/22"

  },
]

3 个答案:

答案 0 :(得分:4)

// 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)
});

答案 1 :(得分:4)

根据Mongoose文档,Mongoose虚拟对象未存储在MongoDB中,这意味着您无法基于Mongoose虚拟对象进行查询。

// Will **not** find any results, because `domain` is not stored in
// MongoDB.
const doc = await User.findOne({ domain: 'gmail.com' });
doc; // undefined

如果要通过计算的属性查询,则应使用自定义设置器或预保存中间件来设置属性。

答案 2 :(得分:-2)

修改您的架构,如下所示:

import itertools

n = int(input())
a = [(True, False) for i in range(n)]
list(itertools.product(*a))

修改您的API调用,如下所示:

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
});