2

Node.JS, MONGODB, not using Mongoose.

I have a document I'm saving. When I use UPSERT, it structures the data as so :

{ "_id" : ObjectId("573a123f55e195b227e7a78d"),
       "document" : 
               [ {"name" : "SomeName" } ]
}

When I use INSERT it inserts it all on the root level :

{ "_id" : ObjectId("573a123f55e195b227e7a78d"), "name" : "SomeName" }

This is obviously going to lead to lots of inconsistencies. I have tried various things. I've tried various methods such as findOneAndReplace, Update with Upsert, I've tried Replace, $setOnInsert. It all does the same thing when Upsert is involved it seems.

I have tried to use document[0] to access the first block of the array, but that throws an error... 'Unexpected Token ['

I have tried various methods and dug for hours through the various documentation, and have searched high and low for someone else having this problem, but it doesn't seem to be well documented issue for anyone else.

Anyone have any recommendations to make sure that all the fields are on the ROOT level, not nested under the variable name? Relevant code below.

findReplace: function(db, document, collection) {

    var dbCollection = db.collection(collection);

    var filter = document.name;

    return new Promise(function(resolve, reject) {
        dbCollection.updateOne({
            "name" : filter
        }, { 
            document
        }, {
            upsert: true
        }, function(err, result) {
            if (err) {
                console.log('error', err)
                reject(err);
            }
            console.log("Found Document and Upserted replacement Document");
            resolve([{'status' : 'success'}]);
        });
    });
}

1 Answer 1

1

When you do this:

{ 
   document
}

You are creating an object containing a document property and the variable's value as its value:

{ 
   document: [ {"name" : "SomeName" } ]
}

This is new functionality from ES6. If you want to access the first item of the document variable, don't create a new object:

return new Promise(function(resolve, reject) {
    dbCollection.updateOne({
        "name" : filter
    }, document[0], { // <========
        upsert: true
    }, function(err, result) {
        if (err) {
            console.log('error', err)
            reject(err);
        }
        console.log("Found Document and Upserted replacement Document");
        resolve([{'status' : 'success'}]);
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thanks! I've been trying to keep up with the ES6 changes, but always something new. It's always the little things.

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.