MongoDB插入字段,它是一个javascript变量

MongoDB inserting field that is a javascript variable?

本文关键字:一个 javascript 变量 字段 插入 MongoDB      更新时间:2023-09-26

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

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

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

您需要使用$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" }