1

So I'm trying to insert a new field into MongoDB, and whilst it will accept my Javascript variable as data, it won't accept it as a new field name:

function appendInformation(question, answer) {
    Sessions.update({ _id: Id }, { question : answer });
}

It inserts the correct answer, but is listed in the doc as question: {answer} not {question} : {answer}

1 Answer 1

4

You need to use $set to update the Session document with a new field.

function appendInformation(question, answer) {
    var qa = { };
    qa[question] = answer;
    Sessions.update({ _id: Id }, { $set : qa });
}

$set documentation

> db.so.remove()
> var qa={"question 1" : "the answer is 1"};
> db.so.insert(qa);
> db.so.find()
{ "_id" : ObjectId("520136af3c5438af60de6398"),
               "question 1" : "the answer is 1" }
> var qa2={"question 2" : "the answer is 2"};
> db.so.update({ "_id" : ObjectId("520136af3c5438af60de6398")}, { $set : qa2 })
> db.so.find()
{ "_id" : ObjectId("520136af3c5438af60de6398"), 
               "question 1" : "the answer is 1",
               "question 2" : "the answer is 2" }
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! Didn't know this, just started working with nosql a couple weeks ago. +1.

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.