如何用猫鼬为单个帖子保存多个类别

问题描述 投票:0回答:1

所以我有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"

我希望帮助您理解为什么会发生此错误,谢谢。

node.js mongodb express mongoose handlebars.js
1个回答
0
投票

👨‍🏫 您可以尝试 below下面的此代码以保存您的游戏和类别。

const jobQuerys = [];

const { category, title, postDescription: description } = req.body;

// save category
category.forEach(categoryName=> {
  const category = new Category({ title: categoryName })
  jobQuerys.push(category.save());
});

// get all category was saved
const categories = await Promise.all(jobQuerys);

// category id temporary
const categoryId = [];

// add category._id to categoriId temporary
categories.forEach(category => {
  categoryId.push(category._id);
});

// save game with categoryId
const game = new Game({ title, description, category: categoryId });
const result = await game.save();

// show result
console.log(result);

💡请确保,因为我们在此代码中使用了await,所以在您的函数中,请添加async

希望它能对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.