【发布时间】:2020-11-01 21:05:03
【问题描述】:
我在我的 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'));
但结果是一样的。
这可能是什么原因,我怎样才能从数组中删除值?
【问题讨论】:
标签: javascript node.js arrays mongodb mongoose