简体   繁体   English

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

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

I want to add a new field (company) to my document.我想在我的文档中添加一个新字段(公司)。 My entire API is:我的整个 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} }}})
};

But the document isn't updating.但是文档没有更新。

Current document:当前文档:

{
_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"
}

But I want to add a company field:但我想添加一个公司字段:

{
    _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"}]
    }

I am using Next.js & MongoDB package.我正在使用 Next.js 和 MongoDB 包。

The problem is that you need to convert the session.id string to a mongo ObjectId(session.id) object:问题是您需要将session.id字符串转换为 mongo ObjectId(session.id)对象:

Take a look at this screenshot using mongo shell :看看这个使用mongo shell 的截图:

No results:没有结果:

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

Found match:找到匹配:

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

On that note, since you're only looking for one document to update, I'd recommend findOne over find .在这一点上,由于您只查找一个要更新的文档,我建议使用findOne 而不是find

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我不能使用 $cond 向 MongoDB 集合添加新字段? 替换式更新不支持错误多更新 - Why I can't use $cond to add a new field to a MongoDB collection? error multi update is not supported for replacement-style update 如何使用现有属性为每个MongoDB文档添加新属性(列)? - How do i add a new attribute (column) to each MongoDB document using an existing attribute? 为什么要在 Next.js 中缓存 MongoDB 连接? 它有效吗? - Why cache MongoDB connection in Next.js? And does it work? LMS 中单个学生的 Next.js/Mongodb 分配状态 - Next.js/Mongodb Assignment Status for Individual Student in a LMS 无法在不同文件中使用 Node.js 将文档插入 Mongodb - Can't insert document into Mongodb using Node.js in different file 无法将新的注册发送到我的数据库mongodb - Can't send a new register to my database mongodb Mongodb $ rename创建新字段,但旧字段保留在文档中 - Mongodb $rename creates new field but old field remains in document 将两个字段的总和添加到文档中的新字段 - Add the sum of two fields to a new field in the document 将新字段添加到 mongoDB 中的特定 object - Add new field to a specific object in mongoDB MongoDB 聚合添加具有多个条件的新字段 - MongoDB aggregate add new field with multiple conditions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM