用猫鼬在元素的id数组中添加/删除元素

时间:2018-06-19 20:57:00

标签: javascript node.js mongoose mongoose-populate

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

 datefrom2      dateto2     value2
    01/01/18      12/31/18       1.02
    01/01/17      12/31/17       1.05

客户端:

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

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

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

有人会知道我的问题来自哪里吗?

2 个答案:

答案 0 :(得分:0)

这是行不通的...我想我在弄错了,但我看不到哪一个

我的代码:

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

答案 1 :(得分:0)

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

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