Mongoose - 在保存文档之前为每个对象生成ObjectID [英] Mongoose - Generate ObjectID for each object before saving document

查看:83
本文介绍了Mongoose - 在保存文档之前为每个对象生成ObjectID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的数组中存在的每个Object生成一个ObjectID。问题是我从其他服务器获取带有.forEach语句的产品,并将它们推送到我的数组中而没有生成ObjectID的Schema ....

I want generate an ObjectID for each Object present inside my array. The thing is I'm getting the products with a .forEach statement from another server and push them inside my array without a Schema that generates an ObjectID....

产品架构:

const productsSchema = new mongoose.Schema({

  apiKey: String,
  domain: String,
  totalcount: Number,
  totaldone: Number,
  allSKUS: Array,
  allProducts: Array,
  created_at: { type: Date },
  updated_at: { type: Date },

}, { collection: 'products', timestamps: true });

productsSchema.plugin(uniqueValidator);

const Products = mongoose.model('Products', productsSchema);

module.exports = Products;

我的代码:

const newProduct = {

  apiKey: userApiProducts.apiKey,
  domain: userApiProducts.domain,
  totalcount: userApiProducts.totalcount,
  totaldone: userApiProducts.totaldone,
  allSKUS: userApiProducts.allSKUS,
  allProducts: userApiProducts.allProducts // generate ObjectID for each object that gets pushed inside the Array
};

Products.findOneAndUpdate( userApiProducts.domain, newProduct, {upsert:true} , (err, existingProducts) => {
  if (err) { return next(err); }
});

输出:

// Please Check ADD OBJECT ID HERE comment. This is where i want to generate an unique ObjectID before I push the data. I tried with var id = mongoose.Types.ObjectId(); but i'm afraid it will not be Unique...

{
        "_id" : ObjectId("58780a2c8d94cf6a32cd7530"),
        "domain" : "http://example.com",
        "updatedAt" : ISODate("2017-01-12T23:27:15.465Z"),
        "apiKey" : "nf4fh3attn5ygkq1t",
        "totalcount" : 11,
        "totaldone" : 11,
        "allSKUS" : [
                "Primul",
                "Al doilea",
                "Al treilea"
        ],
        "allProducts" : [
            {
                // ADD OBJECT ID HERE
                "id": 1,
                "sku": "Primul",
                "name": "Primul",
                "status": 1,
                "total_images": 2,
                "media_gallery_entries": [
                    {
                        "id": 1,
                        "media_type": "image",
                        "label": null,
                        "position": 1,
                        "disabled": false,
                        "types": [
                            "image",
                            "small_image",
                            "thumbnail",
                            "swatch_image"
                        ],
                        "file": "/g/r/grafolio_angel_and_devil.png"
                    },
                    {
                        "id": 2,
                        "media_type": "image",
                        "label": null,
                        "position": 2,
                        "disabled": false,
                        "types": [],
                        "file": "/g/r/grafolio_angel_and_devil_thumbnail.jpg"
                    }
                ]
            },
            {
                // ADD OBJECT ID HERE
                "id": 3,
                "sku": "Al doilea",
                "name": "Al doilea",
                "status": 1,
                "total_images": 2,
                "media_gallery_entries": [
                    {
                        "id": 4,
                        "media_type": "image",
                        "label": null,
                        "position": 2,
                        "disabled": false,
                        "types": [],
                        "file": "/g/r/grafolio_angel_and_devil_thumbnail_1.jpg"
                    },
                    {
                        "id": 5,
                        "media_type": "image",
                        "label": null,
                        "position": 3,
                        "disabled": false,
                        "types": [],
                        "file": "/b/e/before.png"
                    }
                ]
            }, etc ......
        ],
        "__v" : 0,
        "createdAt" : ISODate("2017-01-12T22:58:52.524Z")
}

有没有办法这样做而无需拨打大量的数据库电话?我无法想象这样保存

Is there any way of doing this without having to make a ton of DB Calls? I can't imagine saving like this

array.forEach((x)=> {
    Products.save({})
}) 

希望有人已经在做类似的事情,并找到了完美的解决方案!

Hope someone has already worked on something similar and found the perfect solution for this !

推荐答案

如果你想自动添加 ObjectId ,您需要为它定义一个单独的模式,并将模式的 _id 选项设置为true。

If you want to add ObjectId automatically, you need to define a separate schema for it and set the _id options for the schema as true.

Do以下内容:


  • productsSchema 更改为 CatalogueSchema (为了便于理解
    )。

  • 为Product定义一个新的 ProductSchema (allProducts的元素)

  • 在<$ c中$ c> CatalogueSchema 将allProducts类型定义为 [Product.schema] 。这将自动添加 _id ObjectId )。

  • Change your productsSchema as CatalogueSchema (for ease of understanding).
  • Define a new ProductSchema for Product (element of allProducts)
  • In CatalogueSchema define allProducts type as [Product.schema]. This will automatically add _id (ObjectId).

此外,您不需要添加 created_at updated_at 作为架构的一部分当您将timestamps选项设置为true时。

Also, you don't need to add created_at and updated_at as part of schema when you set timestamps option as true.

目录架构

const Product = require('Product_Schema_Module_Path'); // Edit

const CatalogueSchema = new mongoose.Schema({

    apiKey: String,
    domain: String,
    totalcount: Number,
    totaldone: Number,
    allSKUS: Array,
    allProducts: [Product.schema]   
    // Note the change here (Array -> [Product.schema]
  // Creating a separate schema ensures automatic id (ObjectId)

}, { collection: 'catalogue', timestamps: true });

CatalogueSchema.plugin(uniqueValidator);

const Catalogue = mongoose.model('Catalogue', CatalogueSchema);
module.exports = Catalogue;

产品架构
确保添加ObjectId的新架构

const ProductSchema = new mongoose.Schema({

    id: Number,
    sku: String,
    name: String,
    status: Number,
    total_images: Number,
    media_gallery_entries: Array

}, { _id: true, timestamps: true });  
// _id option is true by default. You can ommit it.
// If _id is set to false, it will not add ObjectId

ProductSchema.plugin(uniqueValidator);

const Product = mongoose.model('Product', ProductSchema);
module.exports = Product;

编辑在目录中保存产品

(另请注意,您必须在CatalogueSchema模块中要求ProductSchema模块)

(Also, note that you have to require the ProductSchema module in your CatalogueSchema module)

// Map userApiProducts.allProducts to array of Product documents
const products = userApiProducts.allProducts.map(product => {
    return new Product(product);
})

const newProduct = {
    apiKey: userApiProducts.apiKey,
    domain: userApiProducts.domain,
    totalcount: userApiProducts.totalcount,
    totaldone: userApiProducts.totaldone,
    allSKUS: userApiProducts.allSKUS,
    allProducts: products
};

Catalogue
    .findOneAndUpdate({ domain: userApiProducts.domain }, newProduct, { upsert:true } , (err, products) => {
    // Handle error
});

这篇关于Mongoose - 在保存文档之前为每个对象生成ObjectID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆