How to check if a node exists?
# help-with-umbraco
t
Hi I'm using Umbraco 13 and creating some nodes. If I run the code again it adds duplicate nodes. I can't find a way to check if the node exists and wonder if there is a way to check before inserting? Thanks
u
I would try 1 first, Get the parent node 2 then, Search for the existing nodes 3 then check if the node exists Then once you have the list of potential matching nodes, you can iterate through them to check if any match your criteria for what you consider a "duplicate" 4: Create the node if it doesn't exists
Copy code
// something like this might work

var contentService = Services.ContentService;
var parent = contentService.GetById(parentNodeId);  // <- This should be your parent nodeID

// Here you pipe in the name of the node you want to check instead of "someNodeName"
var existingNodes = contentService.GetPagedChildren(parent.Id, 0, 1000, out long totalRecords, 
                                filter: IContent x => x.ContentType.Alias == "SomeDocTypeAlias" 
                                && x.Name == "someNodeName");



if (!existingNodes.Any())
{
// so if we are here there is no node and it's safe to create it and then save it
   var newNode = contentService.CreateContent("myNewlyCreatedNode", parent, "SomeDocTypeAlias");
    contentService.SaveAndPublish(newNode);
}
else
{
    // And here the Node already exists and you might wanna do some other stuff
}
And there might be some easier way to do the same thing
a
Basically if you're importing products or similar into Umbraco, you'd want to keep track of them by an ID, key or something like that. Then when running the import, you start by getting the existing products, and adding them to a dictionary - e.g. where the key is the ID (could be a string, an integer or a GUID key) and the value is the
IContent
received from the content service. And when iterating through the product you have from your source (eg an external API), you can check if a product with that ID already exists in the dictionary. This also means that if the product exists in the dictionary, you can get the
IContent
or the product and check whether you need to update it. Dictionaries are much faster for lookups than a list or array, so if you have many products, using a dictionary can help speed up iterating through the products and checking whether they need to be added or updated - or even deleted. You can also read more about this in my old Skrift article: https://skrift.io/issues/importing-external-data-as-content-in-umbraco/ While it was written for Umbraco 7, the concepts are still very valid today. There was also another thread for this a month or so ago for something similar: https://discord.com/channels/869656431308189746/1205078355884376124
5 Views