Reputation: 2292
I'm making a note app, each note will have multiple categories.
var NotesSchema = new mongoose.Schema({
title: String,
note: String,
favorite: {type: Boolean, default: false},
category: [{ type: mongoose.Schema.Types.ObjectId, ref: "categories" }]
},{ timestamps: { createdAt: 'created_at' } });
var Notes = mongoose.model('Notes', NotesSchema);
var CategoriesSchema = new Schema({
name: {type: String, required: true},
favorite: {type: Boolean, default: false},
})
var Categories = mongoose.model('Categories', CategoriesSchema);
I can do this with only one category but I don't know how it's done for multiple categories.
First I thought I need to store the categories, get each id and then store the note. Here's what I tried:
.get('/', (req, res) => {
var data = {
title : "scientific revolution",
note : " some note",
favorite : true,
category : [ 'science', 'books']
}
var catIds = [], seriesIds = [];
data.category.map(cat =>{
const category = new Categories({
name: cat
})
category.save((err,data)=>{
if(err) throw err;
catIds.push(data._id)
})
})
data.category = catIds;
const note = new Notes(data)
note.save((err, data)=>{
if(err) throw err;
res.json(data)
})
})
The catIds
array never gets the ids!
I'm totally new at using references. Didn't even know they existed.
Upvotes: 0
Views: 971
Reputation: 744
Your ref
field should point to the model name not the table name.
In this case Categories
.
I see you have write {ref: 'categories'}
with small c
but mongoose collection name is case sensitive and you should do {ref: 'Categories'}
.
You can read more about mongoose case sensitivity in this post
Upvotes: 1