【发布时间】:2021-04-08 14:50:08
【问题描述】:
抱歉,如果这是一个重复的问题,我的大脑因为看了这么多不同的文章和尝试不同的事情而有点受不了。
使用猫鼬,我目前正在尝试创建一个 PUT 路由,该路由可以采用一组对象并用新的数据集替换整个集合。
我在 put 路由中调用 findOneAndUpdate() 函数时,我尝试使用 save() 函数。但是当我这样做时,它不会用我试图替换的数据替换现有数据,它只是将对象作为新项目添加到集合中并保留现有数据。 findOneAndUpdate() 什么都不做,然后console.log(stats); 触发。
这是我在路由文件中的 PUT 请求:
router.put("/", async (req, res) => {
const { PassingTouchdowns, PassingYards, PlayerID, Receptions, ReceivingTouchdowns, ReceivingYards, RushingTouchdowns, RushingYards, Week } = req.body;
const statsField = {};
if(PassingTouchdowns) statsField.PassingTouchdowns = PassingTouchdowns;
if(PassingYards) statsField.PassingYards = PassingYards;
if(PlayerID) statsField.PlayerID = PlayerID;
if(Receptions) statsField.Receptions = Receptions;
if(ReceivingYards) statsField.ReceivingYards = ReceivingYards;
if(RushingTouchdowns) statsField.RushingTouchdowns = RushingTouchdowns;
if(RushingYards) statsField.RushingYards = RushingYards;
if(Week) statsField.Week = Week;
try {
let playerid = await PlayerGameStatsByWeek.find({ PlayerID });
newStats = new PlayerGameStatsByWeek({
statsField
});
//For Adding multiple objects
req.body.forEach(function(obj) {
var stats = new PlayerGameStatsByWeek(obj);
PlayerGameStatsByWeek.findOneAndUpdate(
playerid,
{ $set: stats },
{ new: true }
);
console.log(stats);
});
res.send({ msg: "Stats Updated!" });
} catch (err) {
console.error(err.message);
res.send({ msg: "Server Error" })
}
});
这是我的模型:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PlayerGameStatsByWeekSchema = Schema(
[{
PassingTouchdowns: String,
PassingYards: String,
PlayerID: String,
Receptions: String,
ReceivingTouchdowns: String,
ReceivingYards: String,
RushingTouchdowns: String,
RushingYards: String,
Week: String
}]
);
const Stats = module.exports = mongoose.model('stats', PlayerGameStatsByWeekSchema);
module.exports.getPlayerGameStatsByWeek = function(callback, limit) {
Stats.find(callback).limit(limit)};
这是我想在 PUT 请求中抛出的一个小例子:
[
{
"PassingTouchdowns": "0",
"PassingYards": "0",
"PlayerID": "123456",
"Receptions": "6.8",
"ReceivingTouchdowns": "0",
"ReceivingYards": "0",
"RushingTouchdowns": "8.5",
"RushingYards": "900.8",
"Week": "1"
},
{
"PassingTouchdowns": "1",
"PassingYards": "14",
"PlayerID": "987654",
"Receptions": "2.5",
"ReceivingTouchdowns": "4",
"ReceivingYards": "30",
"RushingTouchdowns": "0",
"RushingYards": "0",
"Week": "2"
}
]
【问题讨论】:
标签: arrays json mongodb mongoose put