【问题标题】:Update multiple elements with different value in Mongoose在 Mongoose 中更新具有不同值的多个元素
【发布时间】:2022-04-18 15:56:59
【问题描述】:

我有包含列表的文档。假设他们是:

[
 {
  _id: 52b37432b2395e1807000008,
  name: ListA,
  order: 1,
  desc: 'More about List A'
 },
 {
  _id: 52b37432b2395e1807000009,
  name: LISTB,
  order: 2,
  desc: 'More about List B'
 },
 {
  _id: 52b37432b2395e180700000e,
  name: LISTC,
  order: 3,
  desc: 'More about List C'
 },
 {
  ..
 } 
]

现在我想使用批量更新来更改他们的订单字段。我有一个 updated_stage 顺序的 JSON

var updated_stage = [{_id: '52b37432b2395e1807000008', order:2},{_id: '52b37432b2395e180700000e', order:1}, {_id: '52b37432b2395e1807000009', order:3}]

现在我需要使用我拥有的新数组来更新 Mongoose 中的 LIST 模型。我知道我可以使用批量更新来更新具有相同值的多个文档

Model.update({ }, { $set: { order: 10 }}, { multi: true }, callback);

但我必须用不同的值更新它们。我该怎么做?最有效的方法是什么?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    我能想到的最有效的方法是在 updated_stage 数组上运行 forEach 循环。

    现在获取_id 并更新 MongoDB 中现有文档中的顺序。

    【讨论】:

    • 作为旁注,这里是允许该功能的 JIRA:jira.mongodb.org/browse/SERVER-1243
    • 但他正在使用猫鼬 :) @Sammaye
    • MongoDB 中的功能是更新文档中的所有嵌套元素,与 JIRA 应用的 odm 无关
    • 我总是用collection.forEach然后document.save(callback),每次save都有自己的callback,所以最难的就是知道什么时候保存所有的文档!
    • 这很容易检测。取数组的长度,并在每次保存时递减 count 的值。当它等于 0 时表示全部更新。 @damphat
    【解决方案2】:

    这是我用 collection.forEach 进行的测试,然后调用 doc.save:

    我使用 sync.each 来了解所有文档的保存时间

    var mongoose = require('mongoose'), async = require('async');
    
    mongoose.connect('localhost', 'learn-mongoose');
    
    var User = mongoose.model('User', {name: String});
    
    async.series([
        function (done) {
            // remove User collection if exist
            User.remove(done);
        },
    
        function(done) {
            // re-create a collection with 2 users 'Mr One', 'Mr Two'
            User.create([{name: 'Mr One'}, {name: 'Mr Two'}], done);
        },
    
        function(done) {
            // upperCase user.name
            User.find(function(err, users) {
                async.each(users, function(user, callback) {
                    user.name = user.name.toUpperCase();
                    user.save(callback);
                }, done); // done is call when all users are save!!!!
            });
        },
        function(done) {
            // print result
            User.find(function(err, users) {
                console.log(users);
                done();
            });
        },
    ], function allTaskCompleted() {
        console.log('done');
        mongoose.disconnect();  
    });
    

    【讨论】:

      【解决方案3】:

      你们可以使用 mongoose/mongodb bulkwrite 功能。

      Reference

      【讨论】:

        猜你喜欢
        • 2019-03-29
        • 2016-12-29
        • 1970-01-01
        • 2013-02-08
        • 2018-01-24
        • 1970-01-01
        • 1970-01-01
        • 2014-10-29
        • 2019-08-11
        相关资源
        最近更新 更多