如何在JSON的值部分中使用Javascript变量?

时间:2015-10-20 05:26:42

标签: javascript json node.js

var avg_temp = req.params.rating;
var destination = req.params.name;


var temp = { "results.name" : destination }; 


var wew =  {$set: {"results.$.rating" :avg_temp} }; 


mach.update(temp ,wew , function(err,jop){
                if(err)
                {
                    res.status(500);
                    res.send('Destination not found');
                }
                else
                {
                    res.status(202);
                    res.send('Rating is posted');
                }
            });

示例文件:

{
      "_id" :    ObjectId("56247581846ec164bb6be7bf"),
        "results" : [ 
        `enter code here`{
            "name" : "Mk.Mechanics",
            "ph" : NumberLong(9899991817),
            "error" : false,
            "lat" : 28.5833958899999980,
            "lon" : 77.1687398899999980,
            "rating" : 3,
            "add" : "1123, Nanak pura, Delhi, 110021, India",
            "local" : "Nanak pura",
            "city" : "Delhi",
            "contry" : "India"
        }, 
        {
            "name" : "Pahadi",
            "ph" : NumberLong(9876591817),
            "error" : false,
            "lat" : 28.6776553099999990,
            "lon" : 77.2616931799999950,
            "rating" : 3.5000000000000000,
            "add" : "plot-6 saranshpur, Shastri park,Delhi,110018, India",
            "local" : "saranshpur",
            "city" : "Delhi",
            "contry" : "India"
        }, 
        {
            "name" : "mirza",
            "ph" : 1.23123e+007,
            "error" : false,
            "lat" : 28.6775564800000000,
            "lon" : 77.2621437899999960,
            "rating" : 1,
            "add" : " plopur, Shastri park, Delhi,110099,India",
            "local" : "Shastri park",
            "city" : "Delhi",
            "contry" : "India"
        }
] }

标题

当我在目的地和avg_temp中使用静态值时(例如分别为“Pahadi”和12),这可行,但在这种情况下它不会

请求是我正在向节点服务器发送的补丁请求:

localhost:8000\api\machs?name=Pahadi&rating=1

任何想法如何在json中访问JavaScript对象

输出:找不到目的地(尽管我已将确切的字符串值放在名称参数中)

2 个答案:

答案 0 :(得分:0)

只需将console.log(err);放在res.status(500);之上。这样我们就可以知道DB的错误是什么。

答案 1 :(得分:0)

Ahh Silly Mistake,将req.params更改为req.query,因为http请求在查询字符串中发送了值!问题解决了,现在代码工作正常。谢谢大家参与:)