在Mongoose(MongoDB,Node.JS,express)中的对象中创build对象后复制对象

我创build了一个循环来向不同地区添加产品(包含数据)。 首先,我想将所有产品添加到所有地区。 然后,我将(在不同的操作)从这些地区删除产品。

该网站的前提是,对象将能够被一个地区的用户保留,这将使该对象在该地区不可用,但在其他地区仍然可用。 我在注册时保存用户区域,只允许他们查看其区域中可用的对象。

我创build了名为Regions的对象,并将每个产品添加到区域内的数组。 我将它们存储在区域内的原因是未来我期待数以百计的不同产品,并且相信只要返回区域数组中的所有项目在服务器上比在每个产品中单独检查一个数值容易得多。

我的问题是

当运行我的代码,我得到我的网页内的每个对象的重复。

我使用的代码是:

dummyregions.forEach(function(seed){ Region.create(seed, function(err, region){ if(err){ console.log(err); } else { dummyproducts.forEach(function(seedprod){ Product.create(seedprod, function(err, product){ if(err){ console.log(err); } else { region.products.push(product); region.save(); } }); }); } }) }); 

dummyRegions是一个对象,包含名称“string”和数组= []

dummyproducts包含名称“string”,类别“string”和缩略图图片url“string”

我只有4个虚拟产品和3个地区的testing项目,但这是我得到的结果: 每个地区的重复项目

任何帮助将非常感激!

因为Array.forEach阻塞asynchronous方法,你会得到重复。 对于Array.forEach的asynchronous友好版本,您可以使用asynchronous模块或Promises 。

后面可以跟着这个例子(未经testing):

 let regionsPromise = Region.insertMany(dummyregions); let productsPromise = Product.insertMany(dummyproducts); Promise.all([regionsPromise, productsPromise]) .then(([regions, products]) => { console.log(regions); // check regions array console.log(products); // check products array let ids = regions.map(r => r._id); console.log(ids); // check ids Region.update( { '_id': { '$in': ids } }, { '$push': { 'products': { '$each': products } } }, { 'multi': true } ); }) .catch((err) => { /* Error handling */ console.error(`Error ${err.message}`); }); 

和一个使用ES7的async/await

 (async () => { try { const regions = await Promise.all(dummyregions.map(async (reg) => { await Region.create(reg); })); const products = await Promise.all(dummyproducts.map(async (prod) => { await Product.create(prod); })); for (let region of regions) { await region.findByIdAndUpdate(region._id, { '$push': { 'products': { '$each': products } } }); } /* if (regions && regions.length) { await Promise.all( regions.map(async (r) => { await r.findByIdAndUpdate(r._id, { '$push': { 'products': { '$each': products } } }); }) ); } */ } catch (err) { console.error(`Error ${err.message}`); } })();