1

我正在尝试使用 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'插入。我需要传递的值。谁能帮我解决这个问题?

4

0 回答 0