首页 > 解决方案 > 更新一条记录以添加对象错误(NodeJS)

问题描述

我在玩我的 nodjs 和 mongoDB。我发现无法更新对象的错误。

const { MongoClient, ObjectID } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'

const url =
  'mongodb+srv://<user>:<password>@cluster0.uw6pe.mongodb.net/myFirstDatabase?retryWrites=true&w=majority';
console.log(url);
const client = new MongoClient(url);

// Database Name
const dbName = 'studio';

export async function insertData(_id: string) {
  // Use connect method to connect to the server
  await client.connect();
  console.log('Connected successfully to server');
  const db = client.db(dbName);
  const collection = db.collection('shops');

  return new Promise(function (resolve, reject) {
    collection.updateOne(
      { _id: ObjectID(_id) },
      {
        $set: {
          address: {
            type: 'Point',
            coordinates: [123, 321],
          },
        },
      },
      (err, res) => {
        if (err) reject(err);
        resolve(res);
      },
    );
  });
}

我试图通过使用 NestJS 插入地址(对象)。并得到了这个错误。

在此处输入图像描述

所以我想知道我做错了什么。我可以更新键:值,但我不能更新键:对象,如果我输入一个空对象,它可以工作。

有没有人有答案?

标签: javascriptnode.jsmongodbnestjs

解决方案


问题是coordinates: [123, 321]不是有效的坐标,这是因为321不是有效的纬度值。纬度在 -90 到 +90 之间,而经度可以在 -180 到 +180 之间。

线索在错误消息中:"longitude/latitude out of bounds".

如果您确保您的坐标有效,则不应遇到此错误。

有用的阅读文档:


推荐阅读