【问题标题】:Modify Get method to get data using Name修改 Get 方法以使用 Name 获取数据
【发布时间】:2018-06-09 06:25:19
【问题描述】:

我有这样的问题。我正在使用 MongoDB 和 mongoose 创建一个 Nodejs 应用程序。我的数据库中有一个员工集合。该集合的对象具有一些属性,例如 id、name、position、office、Salary。

我已经创建了一个节点函数 get employees using id like this.

router.get('/:id',function (req, res) {
    if(!ObjectId.isValid(req.params.id)){
        return res.status(400).send('No record with given id :$(req.params.id)');
    }

    Employee.findById(req.params.id, function (err, doc) {
        if(!err){
            res.send(doc);
        }

        else{
            console.log('Error in Retriving Employee:'+JSON.stringify(err, undefined, 2));
        }

    });
});

我想修改此函数以使用该名称查找员工。我搜索并尝试了很多示例,但找不到合适的方法。

我试过的一种方法是这样的。

router.get('employee/:name'),function (req, res) {
    Employee.find(req.params.name, function (err, doc) {
        if(!err){
            res.send(doc);
        }

        else{
            console.log('Error in Retriving Employee:'+JSON.stringify(err, undefined, 2));
        }
    });

}

但它并没有给出结果,它只是给了我这样的错误。

Cannot GET /employees/employee/Tharindu

在控制台窗口中,它向我显示这样的。

Refused to load the font '<URL>' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.

有了这个,

Failed to load resource: the server responded with a status of 404 (Not Found)

有人可以帮我解决这个问题吗?谢谢。

【问题讨论】:

  • 您从代码中得到什么输出/错误日志? db.employee.find({'name': nameVariable}); 是一种方法,但如果我有更多信息,我可能会更有帮助! :)
  • 它给了我这样的错误
  • Refused to load the font '&lt;URL&gt;' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.
  • Cannot GET /employees/employee/Tharindu
  • 同时更改您的元安全标签:&lt;meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'" /&gt;

标签: node.js mongodb mongoose


【解决方案1】:

我认为您拨打电话的方式可能有问题 数据库中的集合:

 Employee.find(req.params.name, function (err, doc) {
        if(!err){
            res.send(doc);
        }

我真的认为你应该这样做:

   app.get('employee/:name', function (req, res){
     db.open(function(err,db){ 
         db.collection('employee', function(err, collection) {
             collection.find().toArray(function(err, items) {
                 console.log(items);
                 res.send(items);
             });
         });
     });
});

这将返回数组collection.find().toArray 的结果,其中包含集合中的信息。

此外,使用路径 employee/:name 可能不是最佳做法之一。

【讨论】:

  • 那么将名称传递给该方法的最佳方法是什么?
猜你喜欢
  • 1970-01-01
  • 2015-07-22
  • 2021-11-25
  • 2023-03-26
  • 1970-01-01
  • 2013-01-01
  • 1970-01-01
  • 2012-12-06
  • 2012-08-10
相关资源
最近更新 更多