Adding an item to a collection with Zotero dev in JavaScript

Hello,

I'm trying to create a new collection and to add an item from my library to that collection in JavaScript. I already have the piece of code shown below. But when I run it, the so obtained newCollection happens to be empty, with no trace of the itemWanted. I suspect that the responsible line for this problem is `collection.addItem(item)`, unfortunately I didn't find any doc about this function. I never coded in JavaScript, so please let me know there's any other flaws in the code.

This goes without saying but, my goal is to automatise this process, so that I can later apply it to longer list of wanted items by citationKey (which I think is a feature a better bixtex only).

Cheers,
Jean

`
var collection = new Zotero.Collection();
collection.name = "newCollection";

var fieldName = "citationKey";
var value = "balbus00";
//var value = "itemWanted";
var s = new Zotero.Search();
s.libraryID = Zotero.Libraries.userLibraryID;
s.addCondition(fieldName, 'is', value);
var ids = await s.search();

let item = await Zotero.Items.getAsync(ids[0]);
collection.addItem(item);
var collectionID = await collection.saveTx();
return collection;
`
  • (Please post code questions to zotero-dev. We try to keep technical discussions there.)

    Not sure where you're running this, but make sure you're set up to see errors. This code throws Error: No arguments provided (which is vague, but you could at least find which line was throwing that). You can see this in, for example, the Run JavaScript window.

    Collections have to be saved before items can be added to them, and collection.addItem() doesn't require a separate save. Collection membership is a property of items, so it's really the item that's being saved. item.addToCollection(collectionIDOrKey); item.saveTx() would also work.
  • Sorry I was not aware of this second forum for developers. The error comes from the fact that no item with the wanted citation key is available (one should add an additional check on the length of ids to get rid of it).

    Switching the lines where I save the collection and that where I add an item to it did not help. However, using `item.addToCollection(collectionIDOrKey); item.saveTx()` rather than `collection.addItem(item);` did the trick so thank you very much!
  • @jkpf: Sorry, I thought I triggered No arguments provided with a valid item, but yeah, it was only happening when the search didn't return any results.

    But you were missing an error. collection.addItem() is async, so without an await that doesn't throw properly — it should throw Error: Not in transaction for your code. That function needs to be run from within a transaction. For your purposes, using item.addToCollection() is easier.
  • Many thanks for the explanations!
Sign In or Register to comment.