Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在对象数组上运行mongoose方法_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js 如何在对象数组上运行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,

我的目标是在对象数组上运行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, 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,您可以使用可用的进行检查和计算。