I’m working on a MERN christian social media app that will allow user to share a testimony about their faith. The User modal has a details object with tesitmony, bio, etc. I am trying to query the database to show the last three users where the testimony field is not empty. When the user registers the details object does not exist but when they add a testimony it is created in the db.
The details object in the User modal looks like:
details: {
testimony: {
type: String,
},
bio: {
type: String,
},
}
I found some possible solutions but cann’t get them to work:
const testimony = await User.find({
details: { testimony: { $exists: false } },
})
.sort({ createdAt: 1 })
.limit(3)
.select('-password');
I’ve tried it without the details:
const testimony = await User.find({
testimony: { $exists: true } ,
})
.sort({ createdAt: 1 })
.limit(3)
.select('-password');
With this last one above, if I change $exits: false it will show the last three records with or without the testimony field.
I’ve tried several other suggestions I fouund in other questions but I cannot get anything to work. Anoter one I tried is:
const testimony = await User.find({
testimony: { $exists: true, $ne: [] },
})
.sort({ createdAt: 1 })
.limit(3)
.select('-password');
2
Answers
How about this option:
where:
You match only testimony not null and not empty , you sort based on createdAt filed in DESCENDING order and you limit the number of records in the output to n=2
( note when field do not exist this is equivalent to when the field is null )
The
$exists: true
parameter just filters wherever the that field/object is present in the document irrespective of the value. So, along with$exists: true
use$ne
(not equals) parameter as$ne: ''
to documents where its empty, and$type: 'string'
to omit the ones withnull
.Update your query as:
OR
Use
nin: ['', null]
(not in) to omit all documents with empty field or null.Update your query as:
Hope this helps