Home > front end >  How to add multiple items in model
How to add multiple items in model

Time:10-30

I have a model called "list" where I have to put several items in it. But I made a code that can put only one item in a list. Can anyone help me solve this?

My model:

const mongoose = require('mongoose');

const { itemSchema } = require('./item.js');
const { shopSchema } = require('./shop.js');

const listSchema = mongoose.Schema({
    name: { type: String, required: true },
    created: { type: Date, required: true, unique: true },
    updated: { type: Date },
    items: [itemSchema],
    shop: [shopSchema]
});

module.exports.ListData = mongoose.model("listData", listSchema);
module.exports.listSchema = listSchema;

itemSchema:

const mongoose = require('mongoose');
const categSchema = require("./category.js")

const itemSchema = mongoose.Schema({
    name: { type: String, required: true },
    created: { type: Date, required: true, unique: true },
    category: [categSchema.categorySchema],
    quantity: { type: Number, required: true }
});

module.exports.ItemData = mongoose.model("itemData", itemSchema);
module.exports.itemSchema = itemSchema;

How do I make "items:" to recieve multiple items, not just one? I am using mongodb for this project. Thanks!

CodePudding user response:

Your items already accepts multiple items. Is this not what you want? I tested with this little experiment:

import connect from './db.js';
import mongoose from 'mongoose';

// this just connects to mongodb
await connect();

const itemSchema = mongoose.Schema({
    name: { type: String, required: true }
});
const ItemData = mongoose.model("itemData", itemSchema);

const listSchema = mongoose.Schema({
    name: { type: String, required: true },
    items: [itemSchema]
});

const ListData = mongoose.model("listData", listSchema);
await ListData.deleteMany({});

// create items
await ItemData.create({ name: "potato" });
await ItemData.create({ name: "tomato" });
await ItemData.create({ name: "kitten" });

const items = await ItemData.find({});
await ItemData.deleteMany({});

// create list
await ListData.create({
    name: "Stuff i luv",
    items
});

// get inserted lists
const q = ListData.find();
q.select("-__v -_id -items.__v -items._id");
const ld = await q.exec();

// print results
console.log(JSON.stringify(ld));

// result is 
[{
    "name":"Stuff i luv",
    "items":[{"name":"potato"},{"name":"tomato"},{"name":"kitten"}]
}]

  • Related