Mongoose - InsertMany 方法,upsert:true 是什么意思?

14

我正在使用Mongoose的.insertMany方法,用一个对象数组来填充imagesSchema

想知道如何在.insertMany()或另一种方法中使用upsert:true,以便在第二次运行此函数时更新/删除所有对象。

还想知道如何禁用默认的MongoDB ObjectID生成和_v

模式:

const imagesSchema = new mongoose.Schema(
  {
    catalogue: String,
    productID: String,
    position: Number,
    id: Number,
    name: String,
    alttag: String,
    file: String,
    type: String,
    saved: String,
    status: String
  },
  {
    collection: "images",
    _id: false,
    upsert: true
  }
);
//things that do not work

imagesSchema.plugin(uniqueValidator);

const Images = mongoose.model("Images", imagesSchema);

module.exports = Images;

代码:

Catalogue.findOne({ domain: userApiProducts.domain }, "allProducts", function(
  err,
  products
) {
  if (err) console.error(err);

  (function() {
    var productsARR = [];
    var productsOBJ = { data: [] };

    new Promise(function(resolve, reject) {
      resolve();
    })
      .then(function() {
        var id = 0;

        products.allProducts.forEach(function(x) {
          var catalogueID = x._id;

          for (var i = 0; i < x.media_gallery_entries.length; i++) {
            var filename = x.media_gallery_entries[i].file;
            function type() {
              return filename
                .substr((~-filename.lastIndexOf(".") >>> 0) + 2)
                .toUpperCase();
            }

            id++;

            productsARR.push({
              catalogue: products._id,
              productID: x._id,
              position: x.media_gallery_entries[i].position,
              id: id,
              name: x.name,
              alttag: x.media_gallery_entries[i].label,
              file: x.media_gallery_entries[i].file,
              type: type(),
              saved: "0.00 KB",
              status: "SYNCING"
            });
          }
        });

        if (productsARR.length === productsARR.length) {
          productsOBJ.data = productsARR;
          var arr = productsOBJ.data;
          Images.insertMany(arr, function(error, docs) {});
        }
      })
      .catch(function(e) {
        console.log(e);
      });
  })();
});

      

输出:

{
    "_id" : ObjectId("58795c440d5e554357bfb155"),
    "__v" : 0,
    "catalogue" : "5879356f8d94cf6a32cd7536",
    "productID" : "58795c440d5e554357bfb143",
    "position" : 2,
    "id" : 17,
    "name" : "Al treilea",
    "alttag" : null,
    "file" : "/g/r/grafolio_angel_and_devil_thumbnail_1_1_1_3_3_3.jpg",
    "type" : "JPG",
    "saved" : "0.00 KB",
    "status" : "SYNCING"
},
{
    "_id" : ObjectId("58795c440d5e554357bfb153"),
    "__v" : 0,
    "catalogue" : "5879356f8d94cf6a32cd7536",
    "productID" : "58795c440d5e554357bfb142",
    "position" : 2,
    "id" : 15,
    "name" : "Al treilea",
    "alttag" : null,
    "file" : "/g/r/grafolio_angel_and_devil_thumbnail_1_1_1_1.jpg",
    "type" : "JPG",
    "saved" : "0.00 KB",
    "status" : "SYNCING"
} //etc

输出结果是正确的,但我需要:

  • 找到一种使用upsert:true或查找并删除所有项的方法...
  • 禁用ObjectID生成
  • 禁用_v生成

希望有人已经处理过类似问题,并找到了完美的解决方案!


2
不了解Mongoose,但在底层的MongoDb中,upsert是通过update而不是insert来支持的。在原生的MongoDB中,updateMany是命令,但我不知道它在Mongoose中是否可用:https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/。它需要一个通用的文档过滤器,所以bulk.update可能更合适。 - undefined
3
要禁用ObjectID(_id)和Version(__v),请使用以下模式选项:{ collection: 'images', autoIndexId: false, versionKey: false } - undefined
1个回答

1
要在mongodb中禁用自动ObjectId(autoIndexId),有两种方法。
  1. 如果你想禁用_id字段的自动生成,你可以在插入文档时显式地将其设置为你选择的值。例如:
db.demoCollection.insertOne({ _id: "myCustomID", name: "John Wick", age: 30 });

或者您可以通过在模式中定义来关闭它:
    { collection: 'youCollection', autoIndexId: false}.

关于官方文档中的autoindexid。

要在mongodb中禁用_v,请在定义模式时写入以下内容:

const mySchema = new mongoose.Schema({
  // Your schema fields here...
}, { versionKey: false });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接