Slug Is Not Working While Importing External Data (MongoDB Database)
The issue you're experiencing is because the slug field in Sanity has a specific data structure. When you're importing data and trying to set a slug field, you can't just set it as a string value - you need to provide it in the correct format.
A slug field in Sanity is actually an object with a _type of "slug" and a current property that contains the actual slug string. So when importing your MongoDB data, you need to structure it like this:
{
title: "Your Title from MongoDB",
slug: {
_type: "slug",
current: slugify(yourMongoDBTitle) // your slugified string goes here
}
}Here's a practical example of how to handle this in your import script:
import slugify from 'slugify' // or use any slugification library
// When mapping your MongoDB data to Sanity documents
const sanityDocument = {
_type: 'yourDocumentType',
title: mongoDocument.title,
slug: {
_type: 'slug',
current: slugify(mongoDocument.title, {
lower: true,
strict: true
})
},
// ... other fields
}The key points are:
- The slug field must be an object, not a string
- It must have
_type: "slug" - The actual slug string goes in the
currentproperty
As mentioned in the Sanity documentation on slug generation via API, the automatic slug generation feature only works within Sanity Studio. When importing data programmatically, you need to generate the slugs yourself. Sanity internally uses the speakingurl library, but you can use any slugification library like slugify or write your own function.
If you want to use the same slugification logic that Sanity uses, you could install speakingurl:
npm install speakingurlThen use it in your import:
import getSlug from 'speakingurl'
slug: {
_type: 'slug',
current: getSlug(mongoDocument.title)
}This should resolve your _type mismatch and properly create slug fields during your import process from MongoDB.
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.