javascript - 使用 remove() 删除数组元素不起作用?
问题描述
我在我的 API 中使用以下代码从数组中删除元素
deleteCommentLike: async(req, res) => {
const { error } = createComLikeValidation(req.body);
if (!error) {
const { user_id, comment_id } = req.body;
// const likeModel = new likeSchemaModel({user_id: user_id, post_id: post_id});
await commentlikeSchemaModel
.find({ user_id: user_id, comment_id: comment_id })
.remove();
let commenttData = await commentSchemaModel.findById(comment_id);
console.log(commenttData.usersLiked);
commenttData.likes = --commenttData.likes;
commenttData.usersLiked.remove(user_id);
await commenttData.save();
res.status(200).json({ error: false, data: "done" });
} else {
let detail = error.details[0].message;
res.send({ error: true, data: detail });
}
},
在这里,这一行不起作用:commenttData.usersLiked.remove(user_id);
. 它没有给出任何错误,但user_id
没有从我的数据库中删除。
"use strict";
const mongoose = require('mongoose');
const Joi = require('joi');
var commentSchema = mongoose.Schema({
//other data
usersLiked: [{
type: mongoose.Types.ObjectId,
default: []
}],
//other data
}
var commentSchemaModel = mongoose.model('comments', commentSchema);
module.exports = {
commentSchemaModel,
}
在我的 mongodb 中,它看起来像下面
我已经尝试过使用它,commenttData.usersLiked.remove(mongoose.Types.ObjectId('user_id'));
但结果是一样的。
这可能是什么原因,我如何从数组中删除值?
解决方案
您应该使用更新操作:
commenttData.update({_id: mongoose.Types.ObjectId("5f099..")}, {$set: {usersLiked: yourUpdatedUsersLikedArray}})
当您触发编译器忽略的 js noop时,您期望的 remove() 错误丢失了。
Mongoose 并没有按照你使用它的方式实现属性更新操作。
推荐阅读
- operating-system - 为什么在生产者消费者问题中我们需要 2 个信号量变量?
- r - 如何在ggplot2中绘制具有正确间隔的连续x轴值的箱线图
- java - 无法找到元素的 Spring NamespaceHandler
- python - 如何制作计数器的子集?
- pandas - 使用 matplotlib 计算 pandas 列数据库和条形图中的出现次数
- git - 暂时恢复 git 中的功能
- java - IntelliJ IDEA 在哪里保存运行/调试配置?
- javascript - JsPDF,如何获取 javascript 变量
- detox - 排毒 - 如何在不使用期望的情况下检查元素是否存在
- java - 如何将图像数据复制到 BufferedImage 的子类中?