0

I have a simple NodeJS app which is running a http server that is collecting data from a MongoDB instance and presenting the result as JSON:

db.collection(collectionName).findOne({ '_id': id }, function (err, result) {
        if (err) {
            reportError(err, res);
            return;
        } else {
            outPut(result, res);
        }
});

In the outPut function I'm calling JSON.stringify() on the 'result' variable and writing it in the response. However much of the data is missing, and an empty $db object is included from somewhere. Here is a subset of the data:

"Kommun":1292,
"Lansdel":28,
"Delyta":[
   {
     "$id":"2",
     "$db":""
   },
   {
      "$ref":"691"
   },
   {
      "$ref":"247"
   }

Looking at the record using Studio 3T it seems that all the data I expect has been saved. MongoDb contents

Why am I not getting all my data in the JSON object? Where is the $db coming from? What is it?

5
  • What if you just console.log(result) ? Commented Feb 12, 2018 at 13:44
  • It returns: Delyta: [ DBRef { _bsontype: 'DBRef', namespace: undefined, oid: '2', db: undefined }, { '$ref': '22' } ], Commented Feb 12, 2018 at 14:57
  • Any particular reason why you use the native driver instead of Mongoose? Commented Feb 12, 2018 at 15:14
  • Well since I'm simply saving and loading records I didn't think I'd need much more complex functionality. Will Mongoose solve this problem somehow? Commented Feb 13, 2018 at 15:21
  • Saving and loading records is basically what Mongo does :) And yes, Mongoose makes it both easier and more strict (with data models) Commented Feb 14, 2018 at 8:35

1 Answer 1

1

My guess is that you are using DBRefs. In order to include the referenced data from different collections, you must query those yourself. I cannot show you a code example without some more info on the data schema.

Sign up to request clarification or add additional context in comments.

2 Comments

This may be it. I'm taking the original JSON object from another system and caching it in MongoDB. All the data is present in the single json object, but to handle various cross-references they seem to be using $ref and $id. So, this is impossible to store properly like this? Do I have to save it as a string?
To perhaps make it clearer: the JSON object stored had circular references - represented by $ref and $id couples. While MongoDb seemed happy to save the record based on the object, it's not giving it back properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.