add/remove 将一个元素放入带有猫鼬的对象的 id 数组中

add/remove an element into an id array of an object with mongoose

你好,我有两个模型 user 和 recipe :

const userSchema = new mongoose.Schema({
  _id: {
    type: String,
    required: true
  },
  login: {
    type: String,
    match: /^[a-zA-Z0-9-_]+$/
  },
  password: {
    type: String
  }
});


const recipeSchema = new mongoose.Schema({
  recipeID: {
    type: Number
  },
  title: {
    type: String
  },
  comments: [
    {
      text: { type: String, required: true },
      author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
      postedAt: { type: Date, default: Date.now, index: true },
    },
  ],
  ingredients: [
    {
      ingredient: { type: String, required: true },
      quantity: { type: String },
      unit: {
        type: String,
        default: ''
      },
      index: { type: Number, required: true }
    }
  ],
  steps: [{
    text: { type: String, required: true },
    index: { type: Number, required: true },
  }],
  tags: { type: [String], index: true },
  validatedBy: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
});

客户端:

   function transformUsersToIDs(arr) {
      const userIDs = [];
      arr.forEach((user) => {
         userIDs.push(user._id);
      });
      return userIDs;
    }

...

    const curRecipe = this.state.currentRecipe;
    const valArr = transformUsersToIDs(curRecipe.validatedBy);
    const i = valArr.indexOf(this.state.user._id);
    if (i > -1) {
      curRecipe.validatedBy = valArr.slice(0, i).concat(valArr.slice(i + 1));
    } else {
      curRecipe.validatedBy = valArr.push(this.state.user._id);
    }
    curRecipe.comments.forEach((com) => {
      com.author = com.author._id;
    });

    axios.put(`/api/recipes/${curRecipe.recipeID}`, curRecipe)
      .then((res) => {
        this.setState({ currentRecipe: res.data });
      });

和服务器端:

// update a recipe
  app.put('/api/recipes/:id', (req, res, next) => {
    Recipe.findOne({ recipeID: Number(req.params.id) })
      .exec()
      .then((recipe) => {
        recipe.category = req.body.category;
        recipe.title = req.body.title;
        recipe.comments = req.body.comments;
        recipe.ingredients = req.body.ingredients;
        recipe.steps = req.body.steps;
        recipe.tags = req.body.tags;
        recipe.validatedBy = req.body.validatedBy;

        recipe.save()
          .then(() => res.json(recipe))
          .catch(err => next(err));
      })
      .catch(err => next(err));
  });

并且我尝试通过添加或删除 validatedBy 数组中的元素来更新食谱... 问题是我的食谱已填充,我将 comments.author 转换为字符串(代表用户 ID)并将 validatedBy 转换为字符串数组(代表用户 ID)。当我尝试更新时出现此错误:

ValidationError: Recipe validation failed: comments.0.author: Cast to ObjectId failed for value "@funnybobby" at path "author", validatedBy: Cast to [ObjectId] failed for value "["@funnybobby"]" at path "validatedBy"

有人知道我的问题出在哪里吗?

它不起作用...我想我犯了一个错误,但我看不出是哪一个

我的代码:

Recipe.update({ recipeID: req.params.id }, { $push: { validatedBy: new mongoose.Types.ObjectId(req.body.user) } }, (err) => {
  if (err) {
    next(err);
  } else {
    Recipe.find({ recipeID: Number(req.params.id) })
      .exec()
      .then((recipe) => res.json(recipe))
      .catch(err => next(err));
  }
});

});

错误:错误:传入的参数必须是单个 12 字节的字符串或 24 个十六进制字符的字符串

最后,我找到了解决办法:

 app.put('/api/recipes/validatedBy/add/:id', (req, res, next) => {
    User.findById(req.body.user)
      .then((u) => {
        Recipe.findOne({ recipeID: Number(req.params.id) })
          .populate('validatedBy')
          .then((recipe) => {
            recipe.validatedBy.push(u);
            recipe.save((err) => {
              if (err) {
                res.send(err);
              }
              res.json(recipe);
            });
          });
      })
      .catch(err => next(err));
  });