如何使用 Mongoose 为单个 post 保存多个类别
How to save multiple categories for a single post with Mongoose
所以我有 2 个模式,游戏和类别:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const gameSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
category: [{
type: Schema.Types.ObjectId,
ref: 'category'
}],
});
module.exports = { Game: mongoose.model('game', gameSchema) };
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const categorySchema = new Schema({
title: {
type: String,
required: true
},
});
module.exports = { Category: mongoose.model('category', categorySchema) };
我正在尝试保存包含多个类别的新游戏:
const newGame = new Game({
title: req.body.title,
description: req.body.postDescription,
category: req.body.category,
});
newGame.save().then((game, err) => {
if (err) {
console.log(err)
} else {
req.flash('success-message', 'New Game Created');
res.redirect('/admin/games');
}
});
这是我的前端代码(车把)。我正在使用 jquery 的标签输入插件来获取类别数组
<label for="category">Category</label>
<select multiple name="category" id="category" class="cat form-control">
{{#select game.category}}
{{#each categories}}
<option value="{{title}}">{{title}}</option>
{{/each}}
{{/select}}
</select>
错误:
UnhandledPromiseRejectionWarning: ValidationError: game validation failed: category: Cast to Array failed for value "[ 'ACTION','MOBILE','RPG' ]" at path "category"
我想了解为什么会出现此错误,谢谢。
您可以尝试下面的代码来保存您的游戏和类别。
const jobQuerys = [];
const { category: categories, title, postDescription: description } = req.body;
// save category
categories.forEach(title => {
const category = new Category({ title })
jobQuerys.push(category.save());
});
// get all category was saved
const categoriesResult = await Promise.all(jobQuerys);
// category id temporary
const arrCategoryId = [];
// add category._id to arrCategoryId
categoriesResult.forEach(category => {
arrCategoryId.push(category._id);
});
// save game with categoryId
const game = new Game({ title, description, category: arrCategoryId });
const result = await game.save();
// show result
console.log(result);
Make sure, because we're using await
in this code, so in your function, please add async
.
希望对您有所帮助
所以我有 2 个模式,游戏和类别:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const gameSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
category: [{
type: Schema.Types.ObjectId,
ref: 'category'
}],
});
module.exports = { Game: mongoose.model('game', gameSchema) };
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const categorySchema = new Schema({
title: {
type: String,
required: true
},
});
module.exports = { Category: mongoose.model('category', categorySchema) };
我正在尝试保存包含多个类别的新游戏:
const newGame = new Game({
title: req.body.title,
description: req.body.postDescription,
category: req.body.category,
});
newGame.save().then((game, err) => {
if (err) {
console.log(err)
} else {
req.flash('success-message', 'New Game Created');
res.redirect('/admin/games');
}
});
这是我的前端代码(车把)。我正在使用 jquery 的标签输入插件来获取类别数组
<label for="category">Category</label>
<select multiple name="category" id="category" class="cat form-control">
{{#select game.category}}
{{#each categories}}
<option value="{{title}}">{{title}}</option>
{{/each}}
{{/select}}
</select>
错误:
UnhandledPromiseRejectionWarning: ValidationError: game validation failed: category: Cast to Array failed for value "[ 'ACTION','MOBILE','RPG' ]" at path "category"
我想了解为什么会出现此错误,谢谢。
您可以尝试下面的代码来保存您的游戏和类别。
const jobQuerys = [];
const { category: categories, title, postDescription: description } = req.body;
// save category
categories.forEach(title => {
const category = new Category({ title })
jobQuerys.push(category.save());
});
// get all category was saved
const categoriesResult = await Promise.all(jobQuerys);
// category id temporary
const arrCategoryId = [];
// add category._id to arrCategoryId
categoriesResult.forEach(category => {
arrCategoryId.push(category._id);
});
// save game with categoryId
const game = new Game({ title, description, category: arrCategoryId });
const result = await game.save();
// show result
console.log(result);
Make sure, because we're using
await
in this code, so in your function, please addasync
.
希望对您有所帮助