const tagSchema = new Schema({
name: String
});
const itemSchema = new Schema({
name: String,
tags: [{ type: Schema.Types.ObjectId, ref: 'Tag' }] // Tags referenced by ObjectId
});
const Item = mongoose.model('Item', itemSchema);
const Tag = mongoose.model('Tag', tagSchema);
// Create tags and an item referencing these tags
async function createItemWithTags(name, tagNames) {
const tags = await Tag.insertMany(tagNames.map(name => ({ name })));
const item = new Item({ name, tags: tags.map(tag => tag._id) });
await item.save();
console.log('Item created with referenced tags:', item);
}
createItemWithTags('Laptop', ['electronics', 'computing']);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.