gpt4 book ai didi

javascript - MongoDB 插入字段是一个 javascript 变量?

转载 作者:行者123 更新时间:2023-11-30 10:28:56 25 4
gpt4 key购买 nike

所以我试图将一个新字段插入到 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 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" }

关于javascript - MongoDB 插入字段是一个 javascript 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18085045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com