簡體   English   中英

我無法使用 MongoDB 和 Next.js 向我的文檔添加新字段

[英]I can't add a new field to my document using MongoDB with Next.js

我想在我的文檔中添加一個新字段(公司)。 我的整個 API 是:

import { connectToDatabase } from "../../utils/mongodb";
import { getSession } from 'next-auth/client'


export default async (req, res) => {
  const { db } = await connectToDatabase();
  const { name } = req.body

  const session = await getSession({ req });

  const a = await db
    .collection("users").update({"_id": session.id},{$set: {company: { general: {name: req.body.name} }}})
};

但是文檔沒有更新。

當前文檔:

{
_id: "id"
name: "Test"
email: "test@somemmmail.com"
image: "..."
createdAt: "2020-10-29T16:25:08.908+00:00"
updatedAt: "2020-10-29T16:25:08.908+00:00"
}

但我想添加一個公司字段:

{
    _id: "id"
    name: "Test"
    email: "test@somemmmail.com"
    image: "..."
    createdAt: "2020-10-29T16:25:08.908+00:00"
    updatedAt: "2020-10-29T16:25:08.908+00:00"
    company: [{general: "someinfo"}]
    }

我正在使用 Next.js 和 MongoDB 包。

問題是您需要將session.id字符串轉換為 mongo ObjectId(session.id)對象:

看看這個使用mongo shell 的截圖:

沒有結果:

db.users.find({ "_id": "5fa1e18be3a0523e5ce6c50f" })

找到匹配:

db.users.find({ "_id": ObjectId("5fa1e18be3a0523e5ce6c50f") })

在這一點上,由於您只查找一個要更新的文檔,我建議使用findOne 而不是find

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM