Steve
Steve

Reputation: 4523

MongoError: doc parameter must be an object

I have this xml data which I want to insert into MongoDb.

<?xml version="1.0" encoding="UTF-8"?><PFA><Entity id="123" action="add" date="19-May-2020"></Entity><Entity id="124" action="add" date="29-Jul-2020"></Entity></PFA>

and my nodejs code to insert into mongodb is below:

const fs = require('fs');
const xml2js = require('xml2js');
const util = require('util');

const parser = new xml2js.Parser({
    mergeAttrs: true,
    explicitArray: false
});


fs.readFile('data.xml', (err, data) => {
    parser.parseString(data, (err, result) => {
 
        var jsonString = JSON.stringify(result);
        var jsonObj = JSON.parse(jsonString);

        var MongoClient = require('mongodb').MongoClient;
        var url = "mongodb://localhost:27017/";

        MongoClient.connect(url, function (err, db) {
            if (err) throw err;

            var dbo = db.db("abc");

            // Define which collection to perform insertion
            dbo.collection("entity").insertOne(jsonObj.PFA.Entity, function (err, res) {
                if (err) throw err;
                console.log("1 document inserted");
                db.close();
            });
        });
    });
});

But when I run it, I got error MongoError: doc parameter must be an object

When I console.log(jsonObj.PFA.Entity);, I got the below:

 [   { id: '1227212', action: 'add', date: '19-May-2020' },   { id:
 '1227291', action: 'add', date: '29-Jul-2020' } ]

How come it is not an object even after I have JSON.parse it? How do I then pass it as an object to mongodb? I can't pass the whole jsonObj to mongodb because if I do, I will only get one document inserted instead of two.

Upvotes: 0

Views: 1397

Answers (1)

D. SM
D. SM

Reputation: 14520

 [   { id: '1227212', action: 'add', date: '19-May-2020' },   { id:
 '1227291', action: 'add', date: '29-Jul-2020' } ]

This is an array consisting of two objects (in JS parlance).

If you want to insert multiple documents in a single operation, you can use bulk writes. insertOne requires a single document/object.

Upvotes: 2

Related Questions