I am trying to filter a list of products by a search parameter that will check for products that have the property name and seller.store.name similar (LIKE in php) to the search parameter.
viewAll: async (req, res) => {
const search = req.query.search || '';
const user = User.find({ store.name: { $regex: search, $options: 'i' } });
const filter = search ? {
name: { $regex: search, $options: 'i' },
seller: { user }
} : {};
const products = await Product.find({ ...filter })
.populate('store', 'store.name store.img');
res.send({ products });
},
I am running into two problems.
store.name property using the db.collection.find method. I am getting the error ',' expected.ts(1005). I have tried using both store.name and store['name'].These are my models:
product.js
const mongoose = require('mongoose');
const productSchema = mongoose.Schema({
name: { type: String, required: true },
description: { type: String, required: true },
seller: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
image: { type: String, required: true },
price: { unitPrice: Number, unit: String, required: true },
stock: {
amtAvail: Number,
amtSold: {
type: Number,
default: 0,
},
required: true
},
active: { type: Boolean, required: true, default: true }
}, {
timestamps: true
});
const Product = mongoose.model('Product', productSchema);
module.exports = Product;
user.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
isSeller: { type: Boolean, default: false, required: true },
store: {
type: Object,
name: { type: String, required: true, unique: true },
description: { type: String, required: true },
img: {
profile: String,
header: [String]
},
contact: {
line: String,
phone: Number,
accountNumber: Number
}
},
address: String,
}, {
timestamps: true
});
const User = mongoose.model('User', userSchema);
module.exports = User;
Any help and ideas would be greatly appreciated!