【发布时间】:2019-01-20 04:18:44
【问题描述】:
你好。感谢您点击这篇文章。我想知道如何根据输入字段从 mongodb 获取/查询数据。例如,如果我在名为“位置”的输入字段中输入“美国”,它将只获取其中包含美国的数据,并且数据将显示在下一页上。 当我点击一个按钮时,我如何让它工作。 我将链接我的网站和代码的一些屏幕截图(我感觉我的代码完全错误。)
error im facing after pasting ur code and code for passing data
this is my home.component.html line40. it is to pass the data to next page
this is the page where the data will be displayed
这是我试图弄乱的一些代码(尚未测试是否有效)
//this is in my api.js file
//get data from "listing"(which is my db collection) based on "inputcountry( the inputfield)"
router.get('/home', function(req, res) {
db.collection('listing').find({"inputCountry": req.body.inputCountry}).toArray( (err, results) => {
console.log('got search')
res.send(results)});
});
//this is in my service .ts file (named getservice)
//this is for the searching of house based on location
searchHouse() {
return this.http.get<any[]>('./api/home');
}
//this is in my home. component.ts file (where the searching will happen)
constructor(private fb: FormBuilder, private router: Router, private getService: GetService) {
// Retrieve posts from the API
this.getService.searchHouse().subscribe(searchedhouses => {
this.searchedhouses = searchedhouses;
});
}
<!--this is in my home.component.html where there is the input field named "inputcountry" and submit button -->
<form [formGroup] = "myForm" (ngSubmit) = "searchHouse (myForm)">
<div class="form-group">
<label for="inputCountry">Enter Country</label>
<input type="text" class="form-control" formControlName="inputCountry" id="inputCountry" name = "inputCountry" placeholder="Location e.g Singapore .">
</div>
<button class="btn btn-lg btn-primary btn-block text-uppercase" routerLink="/houses" type="submit" >Find</button>
</form>
【问题讨论】:
-
在更改该输入字段时,使用该输入字段值调用 api。现在在那个api中,在mongo中找到
Regex可能是。并返回值以显示它, -
@saikatchakrabortty 呃我真的不明白你刚才说什么。你介意把它写成答案之一吗?
-
确认我是否这是您想要的,然后将作为答案:代替
{"inputCountry": req.body.inputCountry}do:{"inputCountry": { $regex: req.body.inputCountry ,$options: 'i' }}在.find的查询部分。 -
@saikatchakrabortty $option : 'i' 做什么?我必须安装任何东西才能使正则表达式工作吗?
-
@saikatchakrabortty 是否可以做到,以便当我单击查找按钮时它会获取数据?并在下一页显示?
标签: node.js angular mongodb express mongodb-query