sin*_*Gob 8 mongoose mongodb node.js
如何查询虚拟字段,以便它在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');
});
Run Code Online (Sandbox Code Playgroud)
API调用
app.get('/getAllItems', function(req, res, next) {
Item.find({}, function(err, items) {
res.json(items);
});
});
Run Code Online (Sandbox Code Playgroud)
因此从技术上讲,响应将不包括虚拟时间段.我错过了什么吗?
[
{
name: "nike",
time: "21/2/22"
},
{
name: "adidas",
time: "21/2/22"
},
]
Run Code Online (Sandbox Code Playgroud)
根据 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
Run Code Online (Sandbox Code Playgroud)
如果您想通过计算属性进行查询,则应使用自定义设置器或预保存中间件来设置该属性。
// 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)
});
Run Code Online (Sandbox Code Playgroud)
San*_*was -3
修改您的架构,如下所示:
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
});
Run Code Online (Sandbox Code Playgroud)
按如下方式修改您的 API 调用:
app.get('/getAllItems', function(req, res, next) {
Item.find({}, function(err, items) {
res.json(items.toObject()); // <-- use .toObject() or .toJSON()
});
});
Run Code Online (Sandbox Code Playgroud)