我想为我的数组中存在的每个Object生成一个ObjectID。问题是我从其他服务器获取带有.forEach语句的产品并将其推入我的数组中而没有生成ObjectID的Schema ....
产品架构:
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")
}
有没有办法做到这一点,而不必进行大量的数据库调用?我无法想象这样的保存
array.forEach((x)=> {
Products.save({})
})
希望有人已经开始研究类似的东西并为此找到了完美的解决方案!
答案 0 :(得分:2)
如果要自动添加ObjectId
,则需要为其定义单独的架构,并将架构的_id
选项设置为true。
执行以下操作:
productsSchema
更改为CatalogueSchema
(为了方便)
理解)。 ProductSchema
(allProducts的元素)CatalogueSchema
中,将allProducts定义为[Product.schema]
。这会自动添加_id
(ObjectId
)。此外,当您将timestamps选项设置为true时,您不需要将created_at
和updated_at
添加为架构的一部分。
目录架构
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模块)
// 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
});
答案 1 :(得分:0)
要将多个文档添加到Mongo,您可以使用db.collection.insert()
:
在Mongoose中,您可以使用Model.insertMany()
:
但请记住,当你在Mongoose的其他文档中有一个文档时,它们实际上并没有像Mongo那样存储。 Mongo只存储子文档的ID而不是父文档中的内容 - 甚至不存储这些ID所属的集合的任何信息。
当您使用填充时,Mongoose实际上会在对Mongo的单独请求中从数据库中检索相关文档。因此,人口是猫鼬的概念。 Mongo只存储ID,因此您需要先创建文档,然后才能插入ID。
如果不使用Mongoose,那么你想要做的事就很容易。如果需要,您可以使用自己的ID在Mongo中的一个请求中存储多个文档,并且可以在另一个请求中存储具有这些ID数组的另一个文档。
当然,如果你这样做,你将在操作期间得到不一致的状态,因为Mongo不支持交易。