[英]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.