【发布时间】:2018-06-24 19:09:27
【问题描述】:
我正在尝试从属性模型中获取介于最低价格和最高价格之间的数据
例如,如果用户输入最低和最高价格,那么将显示该最低和最高价格之间的房产数量
我已将 $text 中的类型和标签值编入索引
我是 mongodb 的新手.. 感谢帮助。 谢谢你
这是我的控制器代码
searchProperty = async (req, res) => {
const property = await Property
// first find the property that matches
.find({
$text: {
$search: req.query.q
}
}, {
score: { $meta: 'textScore' }
})
// then sort them
.sort({
score: { $meta: 'textScore' }
})
// limit to only 5 result
//.limit(5)
res.json(property); };
这是我的模型
const propertySchema = new mongoose.Schema({
name: {
type: String,
trim: true,
required: 'Please enter your name!'
},
status: {
type: String,
required: 'Please enter the status!'
},
type: {
type: String,
required: 'Please enter your type!'
},
rooms: {
type: String,
required: 'Please enter your no of Rooms!'
},
old: String,
bedrooms: String,
bathrooms: String,
phone: Number,
title: {
type: String,
trim: true,
required: 'Please enter your property title!'
},
price: {
type: Number,
required: 'Please enter your Price!'
},
area: Number,
description: {
type: String,
trim: true,
required: 'Please enter your description!'
},
zipcode: Number,
slug: String,
tags: [String],
created: {
type: Date,
default: Date.now
},
location: {
type: {
type: String,
default: 'Point'
},
coordinates: [{
type: Number,
required: 'Please enter the Coordinates!'
}],
address: {
type: String,
required: 'Please enter the Address!'
}
},
author: {
type: mongoose.Schema.ObjectId,
ref: 'User',
reuqired: 'You must supply an author'
} });
// Define our indexes
propertySchema.index({
type: 'text',
tags: 'text'
});
这是我的路线
router.get('/api/v1/search', searchProperty);
【问题讨论】:
-
如果您想获得最小值和最大值的结果,为什么要限制结果?我建议您使用带有 $match 的聚合,包括 $text 作为第一阶段,然后在价格上再次使用带有 $gte 和 $lte 的 $match。请参阅下文 - docs.mongodb.com/manual/tutorial/text-search-in-aggregation
-
我已经在代码中注释掉了这个限制,感谢@Avij 的提示
标签: node.js mongodb express mongoose mongodb-query