如何使用mongodb中的对象更新数组?

问题描述 投票:0回答:1

我尝试将geojson对象添加到mongodb中的现有数组,这是我要添加的对象:

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
        }

我尝试使用此mongodb调用没有任何效果:

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);
          });

这什么都不做。 Features是一个数组,其中应包含geojson对象。我该怎么办?

mongodb geojson
1个回答
0
投票

确定,我在此页面上找到了答案:https://www.quora.com/How-do-I-update-a-document-in-mongodb-using-_id-as-query-parameter

为了查询_id,您显然必须先将_id转换为ObjectId。

所以我在这里这样做:

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

然后:

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);
          });

这确实有效! :)

© www.soinside.com 2019 - 2024. All rights reserved.