如何使用 Mongoose 为单个帖子保存多个类别

Posted

技术标签:

【中文标题】如何使用 Mongoose 为单个帖子保存多个类别【英文标题】:How to save multiple categories for a single post with Mongoose 【发布时间】:2020-05-16 04:29:41 【问题描述】:

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

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

【问题讨论】:

这能回答你的问题吗? Mongoose, CastError: Cast to Array failed for value when trying to save a model that contains a model. 不幸的是没有 【参考方案1】:

?‍? 你可以尝试下面的代码?来保存你的游戏和你的类别。

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

?确保,因为我们在这段代码中使用await,所以在你的函数中,请添加async

希望对你有帮助?。

【讨论】:

以上是关于如何使用 Mongoose 为单个帖子保存多个类别的主要内容,如果未能解决你的问题,请参考以下文章

Mongoose – 将对象相互链接而不重复

“查询”计算每个类别 expressjs mongoose 的帖子

Mongoose 查找所有帖子并获取最热门的类别

从单个帖子中获取 Wordpress 类别

NodeJS + Mongoose:MissingSchemaError:模式尚未注册模型“类别”

如何使用多个类别过滤帖子?