Push items into mongo array via mongoose

前端 未结 8 1391
小鲜肉
小鲜肉 2020-11-22 03:22

I\'ve scoured SO a good bit looking for the answer but I\'m sure that I\'m lost for the right words to describe what I\'m after.

Basically I have a mongodb collection

8条回答
  •  死守一世寂寞
    2020-11-22 04:15

    Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };

    There are two options you have:

    Update the model in-memory, and save (plain javascript array.push):

    person.friends.push(friend);
    person.save(done);
    

    or

    PersonModel.update(
        { _id: person._id }, 
        { $push: { friends: friend } },
        done
    );
    

    I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).

    However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when it's absolutely necessary.

提交回复
热议问题