我有以下两个模式:

博客架构:

const blogSchema = new mongoose.Schema(
  {
    title: { type: String, min: 3, max: 20, required: true },
    content: { type: String, required: true },
    likes: { type: Number, required: true, default: 0 },
    author: { type: mongoose.SchemaTypes.ObjectId, ref: "User" },
    comments: [
      { type: mongoose.SchemaTypes.ObjectId, ref: "Comment", default: [] },
    ],
  },
  { timestamps: true, collection: "blogs" }
);

用户架构:

const userSchema = new mongoose.Schema(
  {
    name: { type: String, min: 3, max: 20, required: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, min: 3, max: 50, required: true },
    blogs: [
      {
        type: mongoose.SchemaTypes.ObjectId,
        type: String,
        ref: "Blog",
        required: false,
        default: [],
      },
    ],
    comments: [
      {
        type: mongoose.SchemaTypes.ObjectId,
        type: String,
        ref: "Comment",
        required: false,
        default: [],
      },
    ],
  },
  { timestamps: true, collection: "users" }
);

当我添加一个新博客时,我想要更新用户模式中的博客数组,并向其中添加新的博客ID.我试着这样做:

const { title, content, author } = input;

const newBlog = await Blog.create({
  title: title,
  content: content,
  author: author,
});

let user = await User.findById(author);

await user.updateOne(
  { blogs: [...user.blogs] },
  { $push: { blogs: newBlog } }
);
await user.save();

console.log(newBlog);
return await newBlog.populate("author");

博客被添加到集合中,但用户模型中的数组没有更新. 如果你有什么建议,请让我知道.

推荐答案

您可以在一条UPDATE语句中通过将findByIdAndUpdate$push结合使用来实现这一点.更新如下:

const user = await User.findByIdAndUpdate(author,
   { 
      $push: {
         blogs: newBlog._id
      }
   },
   {new:true}
);

顺便说一句,您的User模式中似乎有一些错误.您在这里为blogscomments定义了type两次:

type: mongoose.SchemaTypes.ObjectId,
type: String,

这应该只保留为type: mongoose.Types.ObjectId.

Javascript相关问答推荐

类型错误:tasks.map不是函数(MERN堆栈)

主要内部的ExtJS多个子应用程序

Cypress -使用commands.js将数据测试id串在一起失败,但在将它们串在一起时不使用命令有效

从实时数据库(Firebase)上的子类别读取数据

if/else JavaScript中的条件行为

提交表格后保留Web表格中的收件箱值?

在页面上滚动 timeshift 动垂直滚动条

如何修复我的js构建表每当我添加一个额外的列作为它的第一列?

如何在Obsidian dataview中创建进度条

配置WebAssembly/Emscripten本地生成问题

我在我的Java代码中遇到了问题,代码的一部分看不到先前定义的对象

Websocket错误—有一个或多个保留位开启:reserved1 = 1,reserved2 = 0,reserved3 = 0

使用Java脚本导入gltf场景并创建边界框

有条件重定向到移动子域

确保函数签名中的类型安全:匹配值

在使用位板时,如何在Java脚本中判断Connect 4板中中柱的对称性?

Next.js中的服务器端组件列表筛选

在不扭曲纹理的情况下在顶点着色器中旋转UV

MongoDB中的嵌套搜索

Pevent触发material 用户界面数据网格中的自动保存