【问题标题】:How can I save array Schema with mongoose?如何使用猫鼬保存数组架构?
【发布时间】:2020-09-05 04:56:55
【问题描述】:

我需要将用户选择的类别(商业、科技、体育...)保存在一个用户集合中,该集合具有一个使用猫鼬的类别数组。

这是我的用户架构和类别数组,我想在其中保存用户类别。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = Schema({
  nick:{
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  categories:[{
    type: String
  }]
});

module.exports = mongoose.model('User', UserSchema);

【问题讨论】:

  • 你有什么错误吗?
  • 不,我想知道我该怎么做
  • 你想在类别中存储数组
  • 我想存储用户在类别数组中选择的类别。

标签: javascript arrays node.js mongodb mongoose


【解决方案1】:

改变

categories: [
  {
    type: String
  }
]

categories: [
   category: {
      type: String
   }
]

【讨论】:

    【解决方案2】:

    你可以试试这个:

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    var UserSchema = Schema({
    
      categories:{
        type: array,
        "default": []
      }
    });
    
    module.exports = mongoose.model('User', UserSchema);
    

    您可以定义类别类型数组并存储 id 和字符串数组

    【讨论】:

      【解决方案3】:

      您的架构对我来说看起来不错。您是在问如何使用已定义的 Schema 将数据实际插入到类别中?

      此外,您可能希望在类别数组架构中添加 _id: false,否则所有条目都会被 mongoose 自动赋予 _id。

      categories:[{
          _id: false,
          type: String
      }]
      

      要将数据插入到类别中,您可以执行以下操作:

      // Get a user for the example.
      const user = await UserModel.findOne({});
      
      // Add the business category to the set. If you just push, then you'll end up with duplicates. AddToSet adds them if they don't already exist. user.categories.addToSet('business');
      await user.save();
      

      当然,你不必为此使用 async await,同样的事情也适用于回调。

      UserModel.findOne({}, function(err, user) {
        if (!err) {
          user.addToSet('business');
          user.save();
        }
      });
      

      【讨论】:

        【解决方案4】:

        您可以通过多种方式实现这一目标

        var Empty1 = new Schema({ any: [] });
        var Empty2 = new Schema({ any: Array });
        var Empty3 = new Schema({ any: [Schema.Types.Mixed] });
        var Empty4 = new Schema({ any: [{}] });
        
        

        为什么你不参考官方文档。 mongoose

        【讨论】:

          【解决方案5】:
          1. 为类别创建单独的架构。
          2. 在用户模式的类别数组中使用 mongoose ref 概念

          例如:

          categories:[
              {type: Schema.Types.ObjectId, ref: 'Categories'}
          ]
          

          【讨论】:

          • 为什么要创建另一个模式来保存数组元素?
          猜你喜欢
          • 1970-01-01
          • 2017-07-23
          • 2021-01-30
          • 1970-01-01
          • 2019-07-14
          • 2017-08-31
          • 2016-05-03
          • 1970-01-01
          • 2018-07-12
          相关资源
          最近更新 更多