Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoosejs text index an object

currently im having a problem regarding referencing text index in object here's the code

Schema

var UserSchema = new mongoose.Schema({
    username: String,
    fullname: String,
    email: {
        type: String,
        lowercase: true,
        unique: true
    },
  supplier: Boolean,
  supplierdetails: {
    name: String,
    businesstype: String,
    location: String,
    products: String,
    revenue: String,
    employees: String,
    yearsestablished: String
  }
});
UserSchema.index({supplierdetails: 'text'});
module.exports = mongoose.model('User', UserSchema);

API

router.post('/findsupplier', function(req, res){
    User.find({supplier: true, $text: {$search: req.body.supplyData}}, {score: {$meta: 'textScore'}})
    .sort({score: {$meta: 'textScore'}})
    .exec(function(err, supplyResult){
        if(err)
            throw err;
        else
            res.json(supplyResult);
    });
});

As you can see here "supplierdetails" is an object on my schema, and i tell mongoosejs to text index it, because i want to do a text index search on the whole supplierdetails object which contains name, businesstype, products, location and etc.., i saw on my mongo shell the created index enter image description here

But it's still not working This is my data on database

enter image description here

I searched "dog" or "shiba" but still returning me no results.

My other functionality which uses text index is perfectly working, the only difference is, the one that i've text index isn't an object, it's just a String property and it perfectly works

Am i doing it wrong?

like image 261
John Avatar asked Mar 19 '26 04:03

John


1 Answers

According to the documentation, you can only create a text index on a String or Array of Strings, not an object (that happens to contain Strings).

like image 152
micah94 Avatar answered Mar 22 '26 00:03

micah94



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!