Problem:
I have the following two schemas:
Blog Schema:
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" }
);
User Schema:
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" }
);
When I add a new blog I want to update the blogs array in the user schema and add the new blog ID to it. I tried to do it like this:
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");
The blog gets added to the collection but the array in the user model doesn’t get updated.
If you have any suggestion please let me know.
Solution:
You can do this in one update statement by combining findByIdAndUpdate
with $push
. Update as follows:
const user = await User.findByIdAndUpdate(author,
{
$push: {
blogs: newBlog._id
}
},
{new:true}
);
As an aside it appears you have some errors in your User
schema. You are defining the type
twice for blogs
and comments
here:
type: mongoose.SchemaTypes.ObjectId,
type: String,
This should just be left as type: mongoose.Types.ObjectId
.