0

I have trouble understanding the syntax of updateOne and insertOne. I know if I don't have a field I can use updateOne and use $set to create a field. But I have an example here

    const  listSchema=new mongoose.Schema({
          name:String,
          items:Array
        });
const List=mongoose.model("List",listSchema);

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

so essentially I already made the field, but I would like to add items into list.items array, so in this case do I use update or insert? And can you tell me some general knowledge about when to use insert and when to use update? Thank you!

Eric
  • 77
  • 9

1 Answers1

1

You need to learn about CRUD generally.

Insert: Nothing exists, but you need to create them.

Update: exists something, you need to add/modify/remove something.

Let's say, here you have empty items. If you have to add items, it falls under update category. There are many ways to update items in mongo[update, updateOne, updateMany, set-update(aggregate)]

Refer this to push item using mongoose

Gibbs
  • 21,904
  • 13
  • 74
  • 138
  • Hey! It's nice to meet you again! So I learned the very basic of CRUD with some youtube tutorials and I am trying to learn deeper. So essentially I know how to create documents and insert them. But with some specific cases I am getting confused about for example here that I have an array. So I didn't know adding new items into the array would fall under the insert category or the update category,but your answer helped me to under stand better and I appreciate your help!!! By the way, in this situation can I use .save() as well since I already have the field created, and it will just update? – Eric Jul 31 '20 at 06:59
  • `save` - if your update doc contains ID, it does update. Else it inserts. So `_id` is the catch with `save`. – Gibbs Jul 31 '20 at 07:00
  • yeah I know that I have to specify a specific Id – Eric Jul 31 '20 at 07:01
  • And another thing is that, with your case, you should use update. Update does update based on condition. Save in the other hand saves the doc which you have. For update, you need to specify the criteria and update doc. For save, you should have doc object. – Gibbs Jul 31 '20 at 07:03
  • I watched a tutorial that first uses findOne to find the document that has the id and then uses .save(). So if I want use .save to update anything, would that be a good idea or a good behaviour to have? – Eric Jul 31 '20 at 07:25
  • That's a valid scenario for save. You read, performed some operations with the date, then you want to save with updated value, you can use save/update. Both are valid here. – Gibbs Jul 31 '20 at 07:43
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/219009/discussion-between-eric-bian-and-gibbs). – Eric Jul 31 '20 at 19:46