使用mongoose(Node.js)创建动态模式?

时间:2013-03-22 13:57:00

标签: node.js mongodb mongoose

我正在尝试使用mongoose在mongoDB中创建动态模式。我使用以下代码

var http = require('http');
var mongoose = require('mongoose'); 
var data = '';
var options = { 
   host: '127.0.0.1', 
   port: 1000, 
   path: '/service',
}; 
var dataDB = mongoose.createConnection('mongodb://localhost/dataDB');
var Schema = mongoose.Schema;
var dataSchema = new Schema({id:String},{strict:false});

http.get(options, function(res) { 
    if (res.statusCode == 200) { 

        res.on('data', function (chunk) { 
            data += chunk;
        });

        res.on('end', function (chunk) { 
            console.log(data);
            var obj = JSON.parse(data);
            var dataLoaddata = dataDB.model('dataSchema', dataSchema, 'data_Load');

            for(var i=0;i<3;i++) {
                console.log(obj.empDetails[i].empName);
                var data1 = 'name';
                var item1 = dataDB.model('data_Load', dataSchema);
                item1.update( { 'id' : i },{data1 : obj.empDetails[i].empName}, { upsert: true }, function (err, numberAffected, raw) {
                    if (err) return handleError(err);
                    console.log('The number of updated documents was %d', numberAffected);
                    console.log('The raw response from Mongo was ', raw);
                });
            }
        });
    } else { 
        console.log("The site is down!"); 
    }
}).on('error', function (e) { 
    console.log("There was an error: " + e.message); 
});

以下是我从特定服务

获得的回复
{
    empDetails: [
        {
            empId: "1",
            empName: "Manoj"
        },
        {
            empId: "2",
            empName: "kumar"
        },
        {
            empId: "3",
            empName: "hello"
        }
    ]
}

我正在尝试在更新操作中动态创建密钥名称,如下所示

var data1 = 'name';
var item1 = dataDB.model('data_Load', dataSchema);
item1.update( { 'id' : i },{`data1` : obj.empDetails[i].empName}, { upsert: true }, function (err, numberAffected, raw){
                    if (err) return handleError(err);
                    console.log('The number of updated documents was %d', numberAffected);
                    console.log('The raw response from Mongo was ', raw);
                });
            }

但是变量没有被解析并作为列插入(意思是说data1的值没有被传递)。它只是作为'data1'插入。我需要传递的值。有人可以帮我解决这个问题吗?

0 个答案:

没有答案