猫鼬切片不限制数组大小

时间:2019-10-30 03:02:59

标签: node.js mongodb mongoose mongoose-schema

我正在开发一个应用程序,但是Mongoose在更新时限制数组大小时遇到​​了问题。我对MongoDB或Mongoose不太熟悉,但我希望这个项目能增加我的知识。我尝试了在SOF上查询过的其他解决方案,但似乎没有一个对我有用。这是我对问题的细分...

:猫鼬5.7.7

摘要:在日志文件中,我希望仅保留10条最新日志,而较旧的日志则从阵列中移出。

问题:对于当前的查询,该分片似乎并没有限制文档的数量。阵列只是继续增长。

ActivityLog.updateOne(
  { guild },
  {
    $push: {
      logs: {
        $each: [{ ...log }]
      },
      $slice: -10
    }
  },
  { upsert: true }
);

1 个答案:

答案 0 :(得分:1)

这实际上可能是实施中的一个问题。这是实际使用中显示其确实有效的基本内容:

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

const uri = 'mongodb://localhost:27017/test';
const options = { useNewUrlParser: true, useUnifiedTopology: true };

mongoose.set("debug", true);
mongoose.set("useFindAndModify", false);
mongoose.set("useCreateIndex", true);

const demoSchema = new Schema({
  _id: Number,
  fifo: [Number]
},{ _id: false });

const Demo = mongoose.model('Demo', demoSchema, 'demo');

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

(async function() {

  try {

    const conn = await mongoose.connect(uri, options);

    await Promise.all(
      Object.values(conn.models).map(m => m.deleteMany())
    );

    let counter = 0;

    await new Promise((resolve, reject) =>
      setInterval(async () => {
        try {
          let result = await Demo.findByIdAndUpdate(
            1,
            { "$push": { "fifo": { "$each": [counter], "$slice": -3 } } },
            { upsert: true, new: true }
          );

          log(result);
        } catch(e) {
          reject(e)
        }
        counter++;
      }, 2000)
    );


  } catch (e) {
    console.error(e);
  } finally {
    mongoose.disconnect();
  }

})()

经过几次迭代(此处为简便起见使用-3),您将看到:

Mongoose: demo.deleteMany({}, {})
Mongoose: demo.findOneAndUpdate({ _id: 1 }, { '$setOnInsert': { __v: 0 }, '$push': { fifo: { '$each': [ 0 ], '$slice': -3 } }}, { upsert: true, remove: false, projection: {}, returnOriginal: false })
{
  "fifo": [
    0
  ],
  "_id": 1,
  "__v": 0
}
Mongoose: demo.findOneAndUpdate({ _id: 1 }, { '$setOnInsert': { __v: 0 }, '$push': { fifo: { '$each': [ 1 ], '$slice': -3 } }}, { upsert: true, remove: false, projection: {}, returnOriginal: false })
{
  "fifo": [
    0,
    1
  ],
  "_id": 1,
  "__v": 0
}
Mongoose: demo.findOneAndUpdate({ _id: 1 }, { '$setOnInsert': { __v: 0 }, '$push': { fifo: { '$each': [ 2 ], '$slice': -3 } }}, { upsert: true, remove: false, projection: {}, returnOriginal: false })
{
  "fifo": [
    0,
    1,
    2
  ],
  "_id": 1,
  "__v": 0
}
Mongoose: demo.findOneAndUpdate({ _id: 1 }, { '$setOnInsert': { __v: 0 }, '$push': { fifo: { '$each': [ 3 ], '$slice': -3 } }}, { upsert: true, remove: false, projection: {}, returnOriginal: false })
{
  "fifo": [
    1,
    2,
    3
  ],
  "_id": 1,
  "__v": 0
}
Mongoose: demo.findOneAndUpdate({ _id: 1 }, { '$setOnInsert': { __v: 0 }, '$push': { fifo: { '$each': [ 4 ], '$slice': -3 } }}, { upsert: true, remove: false, projection: {}, returnOriginal: false })
{
  "fifo": [
    2,
    3,
    4
  ],
  "_id": 1,
  "__v": 0
}
Mongoose: demo.findOneAndUpdate({ _id: 1 }, { '$setOnInsert': { __v: 0 }, '$push': { fifo: { '$each': [ 5 ], '$slice': -3 } }}, { upsert: true, remove: false, projection: {}, returnOriginal: false })
{
  "fifo": [
    3,
    4,
    5
  ],
  "_id": 1,
  "__v": 0
}
Mongoose: demo.findOneAndUpdate({ _id: 1 }, { '$setOnInsert': { __v: 0 }, '$push': { fifo: { '$each': [ 6 ], '$slice': -3 } }}, { upsert: true, remove: false, projection: {}, returnOriginal: false })
{
  "fifo": [
    4,
    5,
    6
  ],
  "_id": 1,
  "__v": 0
}

因此,由于负数的存在,确实确实保留了指定$slice长度和从数组末尾开始的数组,将数组增大到设置的大小,然后删除除最后添加的成员以外的所有成员。