我能够保存新列表并获取所有数据,但我如何在数组下面更新。我需要用forEach更新每个对象,还是用新对象替换它?
模式
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TypeOfAccountSchema = new Schema({
name: {
type: String,
required: true,
unique: true,
},
});
module.exports = mongoose.model('typeofaccount', TypeOfAccountSchema);
[
{
"_id": "5efc26348150a306b017090e",
"name": "Saving Account",
"__v": 0
},
{
"_id": "5efc26348150a306b017090f",
"name": "Current Account",
"__v": 0
},
{
"_id": "5efc26678150a306b0170912",
"name": "Saving1 Account",
"__v": 0
}
]
答案 0 :(得分:0)
您可以使用以下逻辑,而不是使用forEach。
let p = [];
for (let i = 0; i < req.body.length; i++) {
let { _id, ...rest } = req.body[i];
let r = Typeofaccount.update({_id}, {$set: {...rest}})
p.push(r);
}
Promise.all(p)
.then(data => {
res.json({status: 200, message: "Updated"});
})
.catch(err => {
return res.status(500).json({message : err.message})
})