Mongoose multi update

后端 未结 3 897
囚心锁ツ
囚心锁ツ 2021-02-10 16:26

I want to update multiple docs with different values.

My Database looks something like this.

[
    {
        \"_id\": 1,
        \"value\": 50
    },
            


        
3条回答
  •  囚心锁ツ
    2021-02-10 16:58

    First of all your update() query is not ok..

    See documentation for this here

    Model.update(conditions, update, options, callback);

    Suppose your current db model contains docs like this (as you described in question as well):

    [
        {
            "_id": 1,
            "value": 50
        },
        {
            "_id": 2,
            "value": 100
       }
    ];
    

    and you've below array which contains objects (i.e., docs) to be modified with current db's docs to like this:

    idsArray: [
        {
            "_id": 1,
            "value": 4
        },
        {
            "_id": 2,
            "value": 27
        }
    ];
    

    From my experience with mongodb & mongoose, i don't think you can update all docs with single line query (that's you're trying to do).. (P.S. I don't know about that so I am not sure to this..)

    But to make your code work, you will be doing something like this:

    Idea: Loop over each doc in docs i.e, idsArray and call update() over it..

    So, Here's code to this:

    idsArray.forEach(function(obj) {
        Model.update({_id: obj._id}, {$set: {value: obj.value}});
    });
    

    In above code, I am supposing you've _id values in db docs as they 're written above (i.e, "_id": 1).. But if they're like this "_id": ObjectId('1')

    [
      {
        "_id": ObjectId('1'),
        "value": 50
      },
      .....
      .....
    ]
    

    then you'll be need to convert _id to ObjectId(obj._id) in update() query.. so for that you'll be doing like this.

    var ObjectId = require('mongodb').ObjectID;
    
    idsArray.forEach(function(obj) {
       Model.update({_id: ObjectId(obj._id)}, {$set: {value: obj.value}});
    });
    

    P.S. Just confirm it (i.e., _id) before go forward..

    Hope this helps.

    Cheers,

提交回复
热议问题