I got a problem when trying to create a search function in MongoDB, some articles that I read tell find just using a string, not a variable. I need to create a function that can search LIKE in SQL.
async findAllLike(parameter, limit) {
const ctx = "mongodb-findManyLike";
const dbName = await this.getDatabase();
const result = await mongoConnection.getConnection(this.config);
if (result.err) {
logger.log(ctx, result.err.message, "Error mongodb connection");
return result;
}
try {
const cacheConnection = result.data.db;
const connection = cacheConnection.db(dbName);
const db = connection.collection(this.collectionName);
const recordset = await db
.find({ title: { $search: parameter } })
.sort({ createdAt: -1 })
.limit(limit)
.toArray();
if (validate.isEmpty(recordset)) {
return wrapper.error("Data Not Found , Please Try Another Input");
}
return wrapper.data(recordset);
} catch (err) {
logger.log(ctx, err.message, "Error find data in mongodb");
return wrapper.error(`Error Find Many Mongo ${err.message}`);
}
}
Copyright Notice:Content Author:「Just Lovanto」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/74842452/search-like-keyword-mongodb