简体   繁体   English

NodeJS MongoDB动态find()查询

[英]NodeJS MongoDB Dynamic find() Query

I am query mongodb for complete collection in a database by creating dynamic find query using request parameter in express nodejs. 我通过使用express nodejs中的request参数创建动态查找查询来查询mongodb以获取数据库中的完整集合。 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};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM