[英]Can't add custom object into mongoDB Document Array
我試圖在數組中的mongodb文檔中添加一個新對象。
我有一個使用MongoDB的NodeJS項目,該項目有一個名為“ Teste”的集合,我在其中保存了一些隨機數據。
在這些數據中有一個叫做“ ArrayTeste”的數組。 目前,它只保存多個字符串,因為我將輸入命名為相同的東西,因此它會自動為我執行此操作。
但是我不想將每個元素另存為單獨的字符串,我需要獲取這些信息,將它們分組在一個對象中,然后將其添加到數組中。
這是我在NodeJS中的代碼片段:
ServicosModel.prototype.Teste = function (req, res) {
console.log("Metodo Teste");
var query =
{
$push:
{
ArrayTeste:
{
Dado1: req.body.Dado1,
Dado2: req.body.Dado2
}
}
}
console.log(query)
this._connection.open(function (errConn, mongoClient) {
console.log("Entrou open")
if (errConn) {
res.end("Deu erro" + errConn);
}
mongoClient.collection("teste", function (errColl, collection) {
if (errColl) {
res.end("Deu erro" + errColl);
}
console.log("Entrou collection")
collection.update(query, function (errUpdate, result) {
console.log("Entrou update")
if (errUpdate) {
res.end("Deu erro" + errUpdate);
} else {
res.end("Deu certo " + result);
}
});
});
});
}
這是mongoDB文檔結構:
{
"_id" : ObjectId("595bf19febbf3c14e481bc28"),
"id" : "2",
"Titulo" : "TItulo do negocio",
"ArrayTeste" : [
"dado1",
"dado2"
]
}
“ id”參數是我為簡化先前測試中使用的$ elemMatch而創建的參數,因此我不必搜索文檔的_id。
當我運行代碼並將內容插入輸入中時,出現此錯誤:
(節點:8712)UnhandledPromiseRejectionWarning:未處理的承諾拒絕(拒絕ID:1):MongoError:文檔必須是有效的JavaScript對象
而且我完全不知道發生了什么。 該應用程序只是凍結。 我已經搜索了帖子,並嘗試了一些使用$ set和$ addToSet的東西,但是仍然存在相同的錯誤。
任何幫助表示贊賞,在此先感謝!
要更新文檔,您需要兩個強制性參數:
criteria
-選擇要更新的文檔 update
-修改選定的文檔 這是驅動程序文檔: https : //mongodb.github.io/node-mongodb-native/markdown-docs/insert.html#update 。
該錯誤表明collection.update
需要一個對象(第二個參數),並且正在接收一個函數(您的回調函數)。
要使代碼正常工作:
var select = {id: '2'}; // Here we are choosing the document
collection.update(select, query, function (errUpdate, result) {
if (errUpdate) {
res.end("Deu erro" + errUpdate);
} else {
res.end("Deu certo " + result);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.