itsDev018
itsDev018

Reputation: 76

How can I save array Schema with mongoose?

I need to save the categories that a user selected(business, tech, sports...) in a user collection that has a categories array using mongoose.

This is my users Schema and the categories array where I want to save the users categories.

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

Upvotes: 0

Views: 1073

Answers (5)

imfsilva
imfsilva

Reputation: 139

Change

categories: [
  {
    type: String
  }
]

To

categories: [
   category: {
      type: String
   }
]

Upvotes: 1

user10269224
user10269224

Reputation: 73

  1. Create separate schema for categories.
  2. Use mongoose ref concept inside the categories array in user schema

eg:

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

Upvotes: 0

Neel Rathod
Neel Rathod

Reputation: 2111

You can achieve that by various way

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

Why you don't refer official doc for the same. mongoose

Upvotes: 0

Corrie MacDonald
Corrie MacDonald

Reputation: 381

Your Schema looks okay to me. Are you asking how to actually insert data into the categories with the defined Schema?

Also, you might want to add an _id: false to your category array schema, otherwise all entries will automatically be given an _id by mongoose.

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

To insert data into the categories you can do the following:

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

Of course, you don't have to use async await with this, the same thing will work with callbacks.

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

Upvotes: 0

imran ali
imran ali

Reputation: 383

you can try this :

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

var UserSchema = Schema({

  categories:{
    type: array,
    "default": []
  }
});

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

you can define categories type array and store array of ids and string

Upvotes: 0

Related Questions