I am query mongodb for complete collection in a database by creating dynamic find query using request parameter in express nodejs. But no result is found when queried.
const mongo=require('mongodb')
const MongoClient=mongo.MongoClient;
const assert=require('assert');
const express=require('express');
const app=express();
const http=require('http');
const url='http://127.0.0.1:27017';
const port='8000';
const host="localhost";
var server=http.createServer(app);
app.get('/:title',(req, res)=>{
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Authorization');
MongoClient.connect(url, (err, db)=>{
var database=db.db('AppDatabase');
var search=req.params.title;
const query={"search":{search}};
database.collection('testdata').find(query).toArray((err, result)=>{
assert.equal(null,err);
var data=JSON.stringify(result);
res.send(data);
db.close();
});
});
});
server.listen(port, host,()=>{
console.log("running");
});
expected result is a complete collection, and actual result is '[]'.
Impossible to answer definitively without seeing the schema for your database. But I have a suspicion you do not have a dictionary key of "search", but should be "title". I would amend the code so that it looks like this:
var search=req.params.title;
const query={title:search};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.