Eric
Eric

Reputation: 97

How would I insert data into an embeded collection in mongodb

I read through the mongoose and mongo documentation and I still have trouble inserting data into an embedded collection. Here are the two Schema I have

  const  itemSchema=new mongoose.Schema({
      name:String
    });

const Item =mongoose.model("Item",itemSchema);

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

const List=mongoose.model("List",listSchema);

I made a new item

 const item =new Item({
  name: "apple"
});

and I have a new list

const list =new List({
name: "fruits",
items:[]
    });

so now I would like to insert another List item that has a name fruit, but I don't know what parameter I need to use List.insertOne() to target into the items field

Upvotes: 0

Views: 71

Answers (1)

GitGitBoom
GitGitBoom

Reputation: 1912

Your asking how to add an item to an existing document right?

https://mongoosejs.com/docs/subdocs.html#adding-subdocs-to-arrays

https://docs.mongodb.com/manual/reference/operator/update/push/

const myFruitList = await new List({
  name: "fruits",
  items: [{name: "apple"}]
}).save();

// Add another fruit
myFruitList.items.push({name: "bannana"});
await myFruitList.save();

Or using update

await List.updateOne(
  {name: "fruits"},
  {$push: {items: {name: "bananna"}}}
)

Upvotes: 1

Related Questions