【发布时间】: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"
有人知道我的问题出在哪里吗?
【问题讨论】:
标签: javascript node.js mongoose mongoose-populate