Answer the question
In order to leave comments, you need to log in
How to properly filter data in MongoDB?
Hello everyone, please tell me how to do the following filtering in MongoDB?
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', 'чи']
{
"_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 { Schema, model } = require('mongoose')
const bookSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
city: {
type: String,
required: true
},
phoneNumber: {
type: String,
required: true
},
userId: {
type: Schema.Types.ObjectId,
ref: 'User'
}
})
module.exports = model('Book', bookSchema)
exports.searchBook = (req, res, next) => {
console.log(req.body) // ['ne', 'чи']
// just an example of a simple search
// Book.find({
// lastName: 'one'
// })
// .then(book => {
// console.log('book', book)
// })
// .catch(err => {
// if (!err.statusCode) {
// err.statusCode = 500
// }
// next(err)
// })
}
exports.searchBook = (req, res, next) => {
console.log(req.body) // ['ne', 'чи']
const term = req.body.join(' ')
console.log(term)
Book.aggregate([
{
$match: {
$or: [
{
firstName: {
'$regex': term, // 'чи'
'$options': 'i'
}
},
{
lastName: {
'$regex': term,
'$options': 'i'
}
},
{
city: {
'$regex': term,
'$options': 'i'
}
},
{
phoneNumber: {
'$regex': term,
'$options': 'i'
}
}
]
}
}
])
.then(book => {
console.log('book', book)
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500
}
next(err)
})
}
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