[英]add/remove an element into an id array of an object with mongoose
您好,我有兩個模型用戶和配方:
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數組中的元素來更新配方...問題是我的配方已填充,我將comment.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));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.