![](/img/trans.png)
[英]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
[英]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") })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.