如何为数据对象创建动态模型/对象

时间:2016-09-05 18:02:43

标签: java spring mongodb spring-boot

我正在尝试从Mongodb获取其模型/域未知的数据。 我可以使用Mongo模板获得。 e.g。

router.post('/', multer({dest: './uploads/'}).single('file'), function (req, res) {
    var api_request = {};
    api_request.name = req.body.name;
    //add other fields to api_request ...

    var has_file = req.hasOwnProperty('file');

    var io = require('socket.io-client');

    var transaction_sent = false;
    var socket = io.connect('http://localhost:3000');
    socket.on('connect', function () {
        console.log("socket connected to 3000");

        if (transaction_sent === false) {
            var ss = require('socket.io-stream');
            var stream = ss.createStream();

            ss(socket).emit('transaction new', stream, api_request);

            if (has_file) {
                var fs = require('fs');
                var filename = req.file.destination + req.file.filename;

                console.log('sending with file: ', filename);

                fs.createReadStream(filename).pipe(stream);
            }

            if (!has_file) {
                console.log('sending without file.');
            }
            transaction_sent = true;

            //get the response via socket
            socket.on('transaction new sent', function (data) {
                console.log('response from 3000:', data);
                //there might be a better way to close socket. But this works.
                socket.close();
                console.log('Closed socket to 3000');

            });

        }


    });


});

1 个答案:

答案 0 :(得分:1)

您可以使用DBObject。如果你看一下它的实现(BasicDBObject ...),它就是一个包含所有字段的HashMap(键/值):

@Autowired
private MongoTemplate mongoTemplate;

DBObject query  = new BasicDBObject("field", "value");
DBCursor dbCursor = mongoTemplate.getCollection("collectionName").find(query); 

Iterator<DBObject> iterator = dbCursor.iterator();
while(iterator.hasNext()){
    Object value = iterator.next().get("otherfield");
}