2016-11-23 2 views
1

Я довольно новый в узел JS и MongoDB, и мне нужно, чтобы добавить или обновить вложенный документ по сбору MongoDB следующим образом:Добавить и обновить поддокумент MongoDB и узел JS (без мангуста)

{ 
    "_id": "58286e49769e3729e895d239", 
    "id": "2", 
    "title": "Session Title", 
    "sessiondate": "2016-02-11T21:00:00.000Z", 
    "startTime": "14:30", 
    "endTime": "16:30", 
    "breakStartTime": "16:30", 
    "breakEndTime": "18:00", 
    "talks": [ 
     { 
      "id": "3", 
      "title": "Android", 
      "speaker": { 
       "id": "1", 
       "name": "john doe", 
       "about": "about the speaker", 
       "photo": "https://pbs.twimg.com/profile_images/566353055788978177/dUy_ueY2.jpeg" 
      } 
     } 
    ] 
} 

Все решения, которые я нашел, используют мангуст, где в этом конкретном проекте мы решили не использовать мангуст, любые мысли?

ответ

3

Чтобы добавить или обновить во встроенном документе нового talk, вы можете использовать любого из атомной update operators в зависимости от того, как много документов в коллекции вы хотите обновить. Для одного атомного обновления, используйте метод updateOne(), как в следующем примере:

1. Добавление нового вложенного

// Example of adding a subdocument to an existing document. 

var MongoClient = require('mongodb').MongoClient, 
    ObjectId = require('mongodb').ObjectId; 

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { 

    // Get a collection 
    var collection = db.collection('mycollection'); 

    // The new talk document to be added 
    var doc = { 
     "id": "4", 
     "title": "PyData", 
     "speaker": { 
      "id": "7", 
      "name": "alice bob", 
      "about": "about the speaker", 
      "photo": "https://pbs.twimg.com/dUy_ueY2.jpeg" 
     } 
    }; 

    // Update the document with an atomic operator 
    collection.updateOne(
     { "_id": ObjectId("58286e49769e3729e895d239") }, 
     { "$push": { "talks": doc } }, 
     function(err, result){ 
      console.log(result); 
      db.close(); 
     } 
    ) 

}); 

В приведенном выше, можно использовать $push оператор для добавления указанный документ в массив встроенных документов (talks).


2. Обновление существующего поддокумент

// Example of updating an existing subdocument. 

var MongoClient = require('mongodb').MongoClient, 
    ObjectId = require('mongodb').ObjectId; 

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { 

    // Get a collection 
    var collection = db.collection('mycollection'); 

    // Update the document with an atomic operator 
    collection.updateOne(
     { 
      "_id": ObjectId("58286e49769e3729e895d239"), 
      "talk.id": "3" 
     }, 
     { "$set": { 
      "talks.$.title": "Android version 7.0", 
      "talks.$.speaker.name": "foo bar" 
     } }, 
     function(err, result){ 
      console.log(result); 
      db.close(); 
     } 
    ) 

}); 

С существующего обновления документа, вы применяете $set оператора вместе с $ positional operator в вашей операции обновления для изменения встроенных полей документа. $ positional operator идентифицирует правильный элемент в массиве для обновления без явного указания положения элемента в массиве. Для этого, чтобы работать, поле массива должно выглядеть как часть документа запроса, следовательно запрос

{ 
    "_id": ObjectId("58286e49769e3729e895d239"), 
    "talk.id": "3" // <-- array field is part of the query 
} 
0

Посмотрите на Node.JS MongoDB driver

Базового примере

var Db = require('mongodb').Db, 
    MongoClient = require('mongodb').MongoClient, 
    Server = require('mongodb').Server, 
    ReplSetServers = require('mongodb').ReplSetServers, 
    ObjectID = require('mongodb').ObjectID, 
    Binary = require('mongodb').Binary, 
    GridStore = require('mongodb').GridStore, 
    Grid = require('mongodb').Grid, 
    Code = require('mongodb').Code, 
    BSON = require('mongodb').pure().BSON, 
    assert = require('assert'); 

    // Set up the connection to the local db 
    var mongoclient = new MongoClient(new Server("localhost", 27017), {native_parser: true}); 

    // Open the connection to the server 
    mongoclient.open(function(err, mongoclient) { 

    // Get the first db and do an update document on it 
    var db = mongoclient.db("integration_tests"); 
    db.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) { 
     assert.equal(null, err); 
     assert.equal(1, result); 

     // Get another db and do an update document on it 
     var db2 = mongoclient.db("integration_tests2"); 
     db2.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) { 
     assert.equal(null, err); 
     assert.equal(1, result); 

     // Close the connection 
     mongoclient.close(); 
     }); 
    }); 
    }); 
+0

Спасибо за разъяснения, однако я не получаю именно то, что {а: 1}, {Ь: 1 }, и то же самое появляется в документации https://mongodb.github.io/node-mongodb-native/api-generated/collection.html#update, я действительно сбрасываю! –

+0

Как показывает мой пример, мне нужно добавить новый разговор или обновить существующий. –

Смежные вопросы