In my application, I have a User model which contains the fields requests
and followers
, which both store an array of ObjectIds.
const userSchema = new mongoose.Schema({
followers: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
],
requests: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
]
})
I have a query which should push
to the followers
array, each of the id’s in the current documents’s requests
field. Once this has been done, the requests should be then set to an empty array. Here is the query to try accomplish this:
User.updateOne(
{ _id: req.user._id },
{ $push: { followers: { $each: "$requests" } }, $set: { requests: [] } }
)
However, when running this code, I get the following error: CastError: Cast to ObjectId failed for value "$requests" (type string) at path "followers" because of "BSONError"
Any idea why this is error is occuring, and are there any potential solutions I could use in order to perform this query correctly? Thanks.