我有以下两个模式:
博客架构:
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");
博客被添加到集合中,但用户模型中的数组没有更新. 如果你有什么建议,请让我知道.