Search code examples
mongodbgeojson

How do I update an array using an object in mongodb?


I try to add an geojson object to an existing array in mongodb, this is my object that I'd like to add:

const location = {
        type: "Feature",
          properties: {
            description: place.address,
            name: place.name
          },
          geometry: {
            coordinates: [
              place.latLng.latitude,
              place.latLng.longitude
            ],
            type: "Point"
          },
          userIds: [userId],
          id: place.id
        }

I tried using this mongodb call without any effect:

db.collection.updateOne(
          { _id: "5e6e32051c9d4400128cba9c" },
          { $push: { features: location } },
          function(err, result) {
            if (err) {
                reject(err);
            }

            console.log(result);

            console.log("Added new location successfully");
            resolve(true);
          });

This does nothing. Features is an array which should contain geojson objects. What do I do wrong?


Solution

  • Ok, I found the answer on this page: https://www.quora.com/How-do-I-update-a-document-in-mongodb-using-_id-as-query-parameter

    In order to query for an _id you apparently have to convert the _id into an ObjectId first.

    So I did this here:

    const ObjectID = require('mongodb').ObjectID;
    const id = ObjectID("5e6e32051c9d4400128cba9c");
    

    And then:

    db.collection.updateOne(
              { _id: id },
              { $push: { features: location } },
              function(err, result) {
                if (err) {
                    reject(err);
                }
    
                console.log(result);
    
                console.log("Added new location successfully");
                resolve(true);
              });
    

    This did work! :)