【发布时间】:2021-05-03 23:29:31
【问题描述】:
我目前正在开发一个 Pokemon Team Builder 应用程序,该应用程序带有一个 React 前端和一个 Express 后端,带有用于数据库的 MongoDB。
据我所知,我的 TeamSchema 没有这样的原子运算符?这是我的 TeamSchema:
const mongoose = require('mongoose');
const TeamSchema = new mongoose.Schema({
name: {
type: 'String',
required: true,
unique: true,
},
team: [
{
name: { type: String },
types: [{ type: String }],
sprite: { type: String },
},
],
username: {
type: String,
required: true,
},
userId: {
type: String,
required: true,
},
});
const TeamModel = mongoose.model('Team', TeamSchema);
module.exports = TeamModel;
当我尝试通过查找名称和 userId 匹配的团队来调用 findOneAndReplace 方法时,此方法中会引发错误。
const replaceTeam = async (req, res) => {
const { teamName: name, filteredTeam: team } = req.body;
const { username, _id: userId } = req.user;
const newTeam = new Team({ name, team, username, userId });
try {
const replacedTeam = await Team.findOneAndReplace({ name, userId }, newTeam);
console.log(replacedTeam);
res.status(200).json({ message: 'Team was successfully overwritten!' });
} catch (err) {
console.log(err);
res.status(500).json({ message: 'An error occurred while updating the team.' });
}
};
这真是令人头疼,我不确定这里出了什么问题。我几周前才开始使用猫鼬,所以我想知道这是否是我在这里误解的基本问题。
【问题讨论】:
-
您是否尝试过对传入
newTeam的数据执行console.log以确保数据正确,并确认newTeam确实包含有效模型? -
是的,这对我来说确实有效,这是
newTeam为我输出的内容:pastebin.com/BQBj2q1T。话虽如此,它看起来确实像 Team 对象中的 Pokemon 对象本身被赋予了 _id,尽管我从未明确设置过这些。那是原子运算符的来源吗?如果是这样,我能做些什么来规避这种情况并能够成功替换文档? -
我很确定这就是它在谈论原子运算符时所指的内容。
Team是否在const newTeam = new Team行中导入了 MongooseJSTeamModel? -
是在文件顶部:
const Team = require('../models/Team'); -
findOneAndReplace期望的是文档对象,而不是模型。一旦您调用const newTeam = new Team,newTeam 现在就是一个模型,并且已经在数据库中创建。将newTeam创建为具有必填字段的对象,而不是使用new Team,看看是否可行。
标签: javascript node.js mongodb mongoose