【问题标题】:add/remove an element into an id array of an object with mongoose使用猫鼬将元素添加/删除到对象的 id 数组中
【发布时间】:2018-06-23 04:25:33
【问题描述】:

您好,我有两个模型用户和配方:

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));
  });

然后我尝试通过在 validBy 数组中添加或删除元素来更新配方... 问题是我的配方已被填充,我将 cmets.author 转换为字符串(表示用户 ID),并将 validBy 转换为字符串数组(表示用户 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"

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

【问题讨论】:

  • 这里不要使用findsave()...而是使用$push$pull操作符更新mongodb中的数组。
  • 谢谢!我会试试这个

标签: javascript node.js mongoose mongoose-populate


【解决方案1】:

这行不通...我想我犯了一个错误,但我看不出是哪一个

我的代码:

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个十六进制字符的字符串

【讨论】:

    【解决方案2】:

    终于找到了解决办法:

     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));
      });
    

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 2018-05-28
      • 2021-09-08
      • 1970-01-01
      • 2020-06-10
      • 2017-12-22
      • 2019-11-30
      • 2016-01-03
      • 2017-03-28
      相关资源
      最近更新 更多