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}
);
}
{
"_id": 1,
"newPoll": {
[Contents of newPoll]
}
for(var key in newPoll){
var value = newPoll[key];
polls.update(
{ $text: { $search: newPoll.question} }, {'$set' : { [key]: [value]}}, {strict: false}
);
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
);
}