Reputation: 76
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
Reputation: 139
Change
categories: [
{
type: String
}
]
To
categories: [
category: {
type: String
}
]
Upvotes: 1
Reputation: 73
eg:
categories:[
{type: Schema.Types.ObjectId, ref: 'Categories'}
]
Upvotes: 0
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
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
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