1

所以我试图在 中插入一个新字段MongoDB,虽然它会接受我的Javascript变量作为数据,但它不会接受它作为新的字段名称:

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

它插入正确的答案,但在文档中列为question: {answer}{question} : {answer}

4

1 回答 1

4

您需要使用新字段$set来更新文档。Session

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

$set 文件

> 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" }
于 2013-08-06T17:50:38.153 回答