当前位置: 首页 > 知识库问答 >
问题:

findOneandReplace不断给出错误:“错误:替换文档必须不包含原子运算符”?

徐涵亮
2023-03-14
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;
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.' });
  }
};

这真的是一个令人头痛的问题,我不知道这里出了什么问题。我几周前才开始使用猫鼬,所以我想知道这是不是我在这里误解了一些基本的东西。

共有1个答案

华瀚漠
2023-03-14

猫鼬函数findOneAndReplace需要传入一个document对象。请参见下面的代码。

details.findOneAndReplace(
  { location: "New York" },
  { name: "Sunny", age: 292, location: "Detroit" },
  function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  }
);

改变

const newTeam = new Team({ name, team, username, userId })

const newTeam = {name, team, username, userId}
const replacedTeam = await Team.findOneAndReplace({ name, userId }, newTeam);
const replacedTeam = await Team.findOneAndReplace({ name, userId }, newTeam, { new: true });
 类似资料: