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