I would like to update a field that I have on my Post
model. The Post model looks like the following:
const postSchema = new Schema({
title: {
}
likes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User'}],
upvotes: {
type: Number,
default: 0
}
})
I have a database of posts
that I would like to update
by counting their likes
(stored ID's) and update
the upvotes
to the number of likes in the document. Is there a way to do this? I can use the Mongo shell
.
CodePudding user response:
For Mongo version 4.2 you can use pipelined updates to do this, like so:
db.collection.updateMany(
{},
[
{
$set: {
upvotes: {
$size: "$likes"
}
}
}
])
For lesser Mongo versions you'll have to read each document into memory, and execute an update for it.