用不同的值更新 mongoDb collection 每个文档的相同 属性

Update the same property of every document of a mongoDb collection with different values

我在 mongoDb 中有一个 collection,看起来像这样

{ 
"slno" : NumberInt(1),
"name" : "Item 1"
} 
{ 
"slno" : NumberInt(2),
"name" : "Item 2"
} 
{ 
"slno" : NumberInt(3),
"name" : "Item 3"
} 

我收到来自 angularJs 前端的请求,要将此 collection 更新为

{ 
"slno" : NumberInt(1),
"name" : "Item 3"
} 
{ 
"slno" : NumberInt(2),
"name" : "Item 1"
} 
{ 
"slno" : NumberInt(3),
"name" : "Item 2"
} 

我在 Node 6.11 和 express 4.15 中使用 Mongoose 5.0 ORM。请帮助我找到实现此目标的最佳方法。

您基本上需要 bulkWrite(),它可以获取对象的输入数组并使用它来发出 "batch" 更新匹配文档的请求。

假设文档数组在 req.body.updates 中发送,那么您会得到类似

的内容
const Model = require('../models/model');

router.post('/update', (req,res) => {
  Model.bulkWrite(
    req.body.updates.map(({ slno, name }) => 
      ({
        updateOne: {
          filter: { slno },
          update: { $set: { name } }
        }
      })
    )
  })
  .then(result => {
    // maybe do something with the WriteResult
    res.send("ok"); // or whatever response
  })
  .catch(e => {
    // do something with any error
  })
})

这会发送一个请求,输入如下:

bulkWrite([
   { updateOne: { filter: { slno: 1 }, update: { '$set': { name: 'Item 3' } } } },
   { updateOne: { filter: { slno: 2 }, update: { '$set': { name: 'Item 1' } } } },
   { updateOne: { filter: { slno: 3 }, update: { '$set': { name: 'Item 2' } } } } ]
)

在对服务器的单个请求中通过单个响应有效地执行所有更新。

另请参阅 bulkWrite() 上的核心 MongoDB 文档。这是 mongo shell 方法的文档,但所有选项和语法在大多数驱动程序中完全相同,尤其是在所有基于 JavaScript 的驱动程序中。

作为与猫鼬一起使用的方法的完整工作演示:

const { Schema } = mongoose = require('mongoose');

const uri = 'mongodb://localhost/test';

mongoose.Promise = global.Promise;
mongoose.set('debug',true);

const testSchema = new Schema({
  slno: Number,
  name: String
});

const Test = mongoose.model('Test', testSchema);

const log = data => console.log(JSON.stringify(data, undefined, 2));

const data = [1,2,3].map(n => ({ slno: n, name: `Item ${n}` }));

const request = [[1,3],[2,1],[3,2]]
  .map(([slno, n]) => ({ slno, name: `Item ${n}` }));

mongoose.connect(uri)
  .then(conn =>
    Promise.all(Object.keys(conn.models).map( k => conn.models[k].remove()))
  )
  .then(() => Test.insertMany(data))
  .then(() => Test.bulkWrite(
    request.map(({ slno, name }) =>
      ({ updateOne: { filter: { slno }, update: { $set: { name } } } })
    )
  ))
  .then(result => log(result))
  .then(() => Test.find())
  .then(data => log(data))
  .catch(e => console.error(e))
  .then(() => mongoose.disconnect());

或使用 async/await 的更现代的环境:

const { Schema } = mongoose = require('mongoose');

const uri = 'mongodb://localhost/test';

mongoose.Promise = global.Promise;
mongoose.set('debug',true);

const testSchema = new Schema({
  slno: Number,
  name: String
});

const Test = mongoose.model('Test', testSchema);

const log = data => console.log(JSON.stringify(data, undefined, 2));

const data = [1,2,3].map(n => ({ slno: n, name: `Item ${n}` }));

const request = [[1,3],[2,1],[3,2]]
  .map(([slno,n]) => ({ slno, name: `Item ${n}` }));

(async function() {

  try {

    const conn = await mongoose.connect(uri)

    await Promise.all(Object.entries(conn.models).map(([k,m]) => m.remove()));

    await Test.insertMany(data);
    let result = await Test.bulkWrite(
      request.map(({ slno, name }) =>
        ({ updateOne: { filter: { slno }, update: { $set: { name } } } })
      )
    );
    log(result);

    let current = await Test.find();
    log(current);

    mongoose.disconnect();

  } catch(e) {
    console.error(e)
  } finally {
    process.exit()
  }

})()

加载初始数据然后更新,显示响应对象(序列化)和处理更新后集合中的结果项:

Mongoose: tests.remove({}, {})
Mongoose: tests.insertMany([ { _id: 5b1b89348f3c9e1cdb500699, slno: 1, name: 'Item 1', __v: 0 }, { _id: 5b1b89348f3c9e1cdb50069a, slno: 2, name: 'Item 2', __v: 0 }, { _id: 5b1b89348f3c9e1cdb50069b, slno: 3, name: 'Item 3', __v: 0 } ], {})
Mongoose: tests.bulkWrite([ { updateOne: { filter: { slno: 1 }, update: { '$set': { name: 'Item 3' } } } }, { updateOne: { filter: { slno: 2 }, update: { '$set': { name: 'Item 1' } } } }, { updateOne: { filter: { slno: 3 }, update: { '$set': { name: 'Item 2' } } } } ], {})
{
  "ok": 1,
  "writeErrors": [],
  "writeConcernErrors": [],
  "insertedIds": [],
  "nInserted": 0,
  "nUpserted": 0,
  "nMatched": 3,
  "nModified": 3,
  "nRemoved": 0,
  "upserted": [],
  "lastOp": {
    "ts": "6564991738253934601",
    "t": 20
  }
}
Mongoose: tests.find({}, { fields: {} })
[
  {
    "_id": "5b1b89348f3c9e1cdb500699",
    "slno": 1,
    "name": "Item 3",
    "__v": 0
  },
  {
    "_id": "5b1b89348f3c9e1cdb50069a",
    "slno": 2,
    "name": "Item 1",
    "__v": 0
  },
  {
    "_id": "5b1b89348f3c9e1cdb50069b",
    "slno": 3,
    "name": "Item 2",
    "__v": 0
  }
]

这是使用与 NodeJS 兼容的语法 v6.x

对 Neil Lunn 的回答稍作改动就完成了这项工作。

const Model = require('../models/model');

router.post('/update', (req,res) => {

var tempArray=[];

req.body.updates.map(({slno,name}) => {
    tempArray.push({
      updateOne: {
        filter: {slno},
        update: {$set: {name}}
      }
    });
 });

Model.bulkWrite(tempArray).then((result) => {
  //Send resposne
}).catch((err) => {
   // Handle error
});

感谢尼尔·伦恩。