简体   繁体   中英

mongodb inserting subdocuments as : [Object]

i am inserting data into mongodb using mongodb driver in nodejs .

var mongodb = require('mongodb');

var insert = function(uri, collectionName, data, next) {
    mongodb.MongoClient.connect(uri, function(err, driverDb) {  
      if(err) {
        next(err);
      } else {
        driverDb.collection(collectionName).insert(data,function(err,result) {
            if(err) {
                next(err);
            } else {
                driverDb.close(function (err) {
                    if(err) {
                        next(err);
                    } else {
                        next(null,result);
                    }
                });
            }
        });
      }
    });
};


insert('mongodb://localhost/mean-test','testcol',{ 
             a : 'Apple',
             b : [ { ba: 'Boy' }, {bb : 'Bird'} ]
        }, function(err,models) {
            console.log(models);
        });

The above result into following:

[{a:'Apple', b : [[Object]] }]  

How do i achieve this :

[{_id:ObjectId("someid"), a:'Apple', b : [{_id:ObjectId("someid"), ba: 'Boy' }, {_id:ObjectId("someid"), bb : 'Bird'}] }]

Please note i do not want to use any other npm module except of mongodb . also i want to insert in one db query.

Your objects are inserting correctly, it's just that console.log only shows two levels of object detail by default. To show all object levels you need to call util.inspect directly so you can control that:

console.log(util.inspect(models, {depth: null}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM