Node.js 如何在对象数组上运行mongoose方法
我的目标是在对象数组上运行mongoose方法。比如说Node.js 如何在对象数组上运行mongoose方法,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我的目标是在对象数组上运行mongoose方法。比如说 const ItemSchema = mongoose.Schema({ name: String, time: { type: Number, default: 24 } }); ItemSchema.methods.minus2 = function() { this.time -= 2; this.save(); } Api方法 app.get('/allItems', function(req,
const ItemSchema = mongoose.Schema({
name: String,
time: { type: Number, default: 24 }
});
ItemSchema.methods.minus2 = function() {
this.time -= 2;
this.save();
}
Api方法
app.get('/allItems', function(req, res) {
Item.find({}, function(err, items) {
// I want to run items.calculateTime(); but it is not possible.
// How would I run calculateTime function on the array of objects?
});
});
你的总体目标是什么?是否要在结果中包含计算字段?您的MongoDB服务器版本是什么?我想更新时间字段。服务器版本为3.0.6时间字段可能会更改。所以这就是我需要检查的原因。我觉得这种方法效率不高,但我想不出任何解决方案来更新时间字段。我应该在模式上使用
pre
方法吗?我想您可能希望使用aggregate()
函数而不是find()
获取allItems API,您可以使用可用的进行检查和计算。