Pergunta

I am working on a Meteorjs application which is using MongoDB in back end. In my collection there are some objects which are having a common field named parent_id eg

{name:'A',parent_id:'acd'}
{name:'b',parent_id:'acd'}
{name:'c',parent_id:'acd'}
{name:'d',parent_id:'acd'}

I want to copy all these objects in the database by changing the parent_id field eg

{name:'A',parent_id:'acdef'}
{name:'b',parent_id:'acdef'}
{name:'c',parent_id:'acdef'}
{name:'d',parent_id:'acdef'}

and these all objects will be in database like this

{name:'A',parent_id:'acd'}
{name:'b',parent_id:'acd'}
{name:'c',parent_id:'acd'}
{name:'d',parent_id:'acd'}
{name:'A',parent_id:'acdef'}
{name:'b',parent_id:'acdef'}
{name:'c',parent_id:'acdef'}
{name:'d',parent_id:'acdef'}

for this I have find the elements from the db which have parent_id:'abc' items=db.collection.find({parent_id:'abc').fetch() and using a loop i have changed the parent_id of each item and then tried this command

for(i=0;i<items.length;i++){
    items[i].parent_id='abcdef';
    meteor.collection.insert(item)
}

but it is giving me an errorduplicate for _id

Foi útil?

Solução

Well it will unless you delete the _id value from the object first:

for(i=0;i<items.length;i++){
    items[i].parent_id='abcdef';
    delete items[i]["_id"];
    meteor.collection.insert(item[i])
}

So the delete should clear that up and an new _id will be generated.

Outras dicas

When you Collection.find() your documents you can use the field specifier to exclude the _id field.

var items = collection.find({}, {fields: {name: 1, parent_id: 1, _id: 0}).fetch();

Then when you modify and insert those documents again, they will be duplicates with each having its own unique _id.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top