Reputation: 5265
I am making an array to array search function. I have a schema which looks like this:
var PostSchema = new Schema({
title: String,
pieces: Array,
category: Schema.ObjectId
});
The pieces
field is an array of the title
field but it has been split into pieces with title.split(' ');
.
So if the title looks like this: Lorem ipsum doler sit amet
the pieces looks like this: [ 'Lorem', 'ipsum', 'doler', 'sit', 'amet' ]
Now I got this search function that where I split the search input as well which I want to check against the pieces
field in order to find the best results.
If I search for Lorem doler amet
it becomes [ 'Lorem', 'doler', 'amet' ]
.
The way I'm trying to do this is through this code:
var searchString = req.body.searchString;
Post
.find({})
.where('pieces').in(searchString.split(' ')) // The pieces must have ALL of the items from splitted searchString.
.limit(30)
.select('-_id -_v -pieces')
.exec(function (err, posts) {
// Do stuff
});
But it does not seem to work at all. Any clues on how I can make such a search function with Mongoose?
To simplify what I'm trying to do:
check if
[ 'Lorem', 'ipsum', 'doler', 'sit', 'amet' ]
contains ALL of
[ 'Lorem', 'doler', 'amet' ]
Upvotes: 0
Views: 352
Reputation: 1245
I do believe what you looking for is the $all operator. Your mongoose code should be as follows:
var searchString = req.body.searchString;
Post
.find({})
.where('pieces').all(searchString.split(' '))
.limit(30)
.select('-_id -_v -pieces')
.exec(function (err, posts) {
// Do stuff
});
I hope it helps.
Upvotes: 3
Reputation: 312129
You can use $all
to perform a query against an array field that must contain all of a specified set of elements.
In Mongoose, you can do this using Query#all
as:
Post
.find({})
.where('pieces').all(searchString.split(' '))
.limit(30)
.select('-_id -_v -pieces')
.exec(function (err, posts) {
// Do stuff
});
Upvotes: 2