Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

443
Visualizações
findByIdAndUpdate extracción de objetos de matriz igual a un valor específico

Quiero eliminar uno o más objetos de tipo tweet de la lista de la timeline de tiempo dentro del modelo de usuario. Los objetos de tweet que quiero eliminar son aquellos cuya identificación de autor coincide con una identificación específica user._id .

He intentado esto:

 router.get("/follow/:userId", isLoggedIn, catchAsync(async (req, res) => { try { const currentUser = await User.findById(req.user._id).populate("timeline") const user = await User.findById(req.params.userId).populate("followers tweets") for (let tweet of currentUser.timeline) { if (tweet.author._id.equals(user._id)) { currentUser.timeline.pull(tweet._id) } } req.flash("error", `Unfollowed to ${user.username}`) user.save(); currentUser.save() res.redirect(`/${user._id}`) } catch (err) { req.flash("error", err.message); res.redirect("back") } }));

y esto:

 await User.findbyIdAndUpdate(currentuser._id, { $pull: { timeline: { author : user._id } } }

pero ninguno de ellos está trabajando.

Mi modelo de usuario:

 const userSchema = new Schema({ name: { type: String, required: true }, biography: { type: String, maxlength: 160 }, location: {type: String, maxlength: 30 }, email: { type: String, unique: true, required: true }, image: { url: String, filename: String, }, followers: [{ type: Schema.Types.ObjectId, ref: "User" }], following: [{ type: Schema.Types.ObjectId, ref: "User" }], tweets: [{ type: Schema.Types.ObjectId, ref: "Tweet"}], timeline: [{ type: Schema.Types.ObjectId, ref: "Tweet"}] });

Mi modelo de tuit:

 const tweetSchema = new Schema({ images: [{ url: String, filename : String }], text: { type: String, maxlength: 260}, date: { type: Date, default: Date.now }, author: { type: Schema.Types.ObjectId, ref: "User" }, parent: { type: Schema.Types.ObjectId, ref: "Tweet", default:null }, replies: [{ type: Schema.Types.ObjectId, ref: "Tweet" }], likes: [{ type: Schema.Types.ObjectId, ref: "User" }], retweets: [{ type: Schema.Types.ObjectId, ref: "Tweet" }], retweetStatus: {type: Schema.Types.ObjectId, ref: "Tweet", default: null} });
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Si tu colección se ve así:

 [ { "_id" : ObjectId("60254276259a60228cbe5707"), "name" : "Mary", "timeline" : [ ObjectId("60254276259a60228cbe5703"), ObjectId("60254276259a60228cbe5704"), ObjectId("60254276259a60228cbe5705") ] }, { "_id" : ObjectId("60254276259a60228cbe5706"), "name" : "Dheemanth", "timeline" : [ ObjectId("60254276259a60228cbe5700"), ObjectId("60254276259a60228cbe5701"), ObjectId("60254276259a60228cbe5702") ] } ]

entonces la solución es:

 usersSchema.updateOne( { "_id": ObjectId("60254276259a60228cbe5706"), "timeline": ObjectId("60254276259a60228cbe5700"), }, { $pull: { "timeline": ObjectId("60254276259a60228cbe5700") } } ) .then() .catch() // or usersSchema.findOneAndUpdate( { "_id": ObjectId("60254276259a60228cbe5706"), "timeline": ObjectId("60254276259a60228cbe5700"), }, { $pull: { "timeline": ObjectId("60254276259a60228cbe5700") } }, { new: true } ) .then() .catch()
over 4 years ago · Santiago Trujillo Relatório

0

¡Finalmente encontré el problema! El problema que estaba teniendo es que estaba tratando de eliminar elementos de una lista de objetos mientras recorría esa lista. La solución es fácil: puede simplemente crear una matriz vacía auxiliar y empujar los elementos que desea eliminar, luego recorrer esa matriz auxiliar y extraer los elementos de la matriz original.

En mi caso, ya tengo un array con los tweets que quería eliminar, user.tweets . La solucion es:

 router.get("/follow/:userId", isLoggedIn, catchAsync(async (req, res) => { try { const currentUser = await User.findById(req.user._id).populate("timeline") const user = await User.findById(req.params.userId).populate("followers tweets") for (let tweet of user.tweets) { currentUser.timeline.pull(tweet._id) } req.flash("error", `Unfollowed to ${user.username}`) user.save(); currentUser.save() res.redirect(`/${user._id}`) } catch (err) { req.flash("error", err.message); res.redirect("back") } }));
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda