Answer the question
In order to leave comments, you need to log in
Why doesn't MongoDB full-text search on multiple fields work?
Hello. Can you please tell me why the full-text search in MongoDB for several fields does not work? Where did I go wrong in the code?
I have three documents.
{
"_id": {
"$oid": "5d7f70d46b647c1a74d9b8aa"
},
"firstName": "user",
"lastName": "one",
"phoneNumber": "+7 (111) 111-11-11",
"city": "Москва",
"userId": {
"$oid": "5d5ea4596886b1107c2be849"
},
"__v": 0
}
{
"_id": {
"$oid": "5d7f70d46b647c1a74d9b8aa"
},
"firstName": "user",
"lastName": "two",
"phoneNumber": "+7 (222) 222-22-22",
"city": "Сочи",
"userId": {
"$oid": "5d5ea4596886b1107c2be849"
},
"__v": 0
}
{
"_id": {
"$oid": "5d7f70d46b647c1a74d9b8aa"
},
"firstName": "user",
"lastName": "two",
"phoneNumber": "+7 (333) 333-33-33",
"city": "Москва",
"userId": {
"$oid": "5d5ea4596886b1107c2be849"
},
"__v": 0
}
'ne чи'
firstName
lastName
city
{
"_id": {
"$oid": "5d7f70d46b647c1a74d9b8aa"
},
"firstName": "user",
"lastName": "one",
"phoneNumber": "+7 (111) 111-11-11",
"city": "Москва",
"userId": {
"$oid": "5d5ea4596886b1107c2be849"
},
"__v": 0
}
{
"_id": {
"$oid": "5d7f70d46b647c1a74d9b8aa"
},
"firstName": "user",
"lastName": "two",
"phoneNumber": "+7 (222) 222-22-22",
"city": "Сочи",
"userId": {
"$oid": "5d5ea4596886b1107c2be849"
},
"__v": 0
}
const mongoose = require('mongoose')
const bookSchema = new mongoose.Schema(
{
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
city: {
type: String,
required: true
},
phoneNumber: {
type: String,
required: true
},
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}
)
// Define our indexes
bookSchema.index({
firstName: 'text',
lastName: 'text',
city: 'text'
})
module.exports = mongoose.model('Book', bookSchema)
exports.searchBook = async (req, res, next) => {
const term = 'ne чи'
console.log(term)
const books = await Book.find({
$text: {
$search: term
}
}, {
score: { $meta: 'textScore' }
})
.sort({
score: { $meta: 'textScore' }
})
console.log('books', books)
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question