CrumrineCoder CrumrineCoder - 3 years ago 165
Node.js Question

Replace a JSON document with another in MongoDB & Mongoose without knowing the properties of the JSON document beforehand

I've been at this problem for a few days now so I'm asking here now. I'm writing a poll app and the user can link a poll to their account if they're logged in. They can then edit the poll afterwards and how I've done it is copy the create a poll form but filled in the data already put in. The JSON document is made just fine, but the problem I am running into is attempting to replace the original document with the new one. I've made several solutions that don't work, but here's the closest one. In my Polls Mongoose Schema file, I have this router function:

var polls = db.collection('polls');
module.exports.replace = function(newPoll, callback){
polls.replaceOne(
{ $text: { $search: newPoll.question} }, {newPoll}
);
}


Unfortunately, this is the result:

{
"_id": 1,
"newPoll": {
[Contents of newPoll]
}


}

I want the contents of the newPoll to be "one step up" if that makes sense, but I couldn't figure that out. So I tried removing the old document's contents and looping through the JSON document and adding it to the old poll one by one, but the data wouldn't save.

for(var key in newPoll){
var value = newPoll[key];
polls.update(
{ $text: { $search: newPoll.question} }, {'$set' : { [key]: [value]}}, {strict: false}
);


}

I'm still new to this, so I'm sorry if the solution is obvious but I've tried and my Google-fu is yielding no results that have worked.

Answer Source

In this code:

var polls = db.collection('polls');
module.exports.replace = function(newPoll, callback){
  polls.replaceOne(
     { $text: { $search: newPoll.question} }, {newPoll}
  );
}

{newPoll} is equivalent to {newPoll: newPoll}. That is the reason for the structure of inserted document. Assuming newPoll is an object you should do it like this:

var polls = db.collection('polls');
module.exports.replace = function(newPoll, callback){
  polls.replaceOne(
     { $text: { $search: newPoll.question} }, newPoll
  );
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download