下面是聊天应用程序的nodejs服务器的代码和mongoose模式的一部分。当用户发送消息时,该消息保存在两个文档中。一个在发送方,另一个在接收方。
在下面给出的JS代码中,我试图从发送者文档和接收者文档中删除发送者消息。删除发件人消息文档很简单:Message.findByIdAndDelete({_id:userID}).catch((err) => { console.log(err.message);});
至于删除接收方文档中的发送方项目,我设法找到了包含senderID的接收方文档,但当我尝试从接收方文档的用户列表中提取该项目时,我得到了以下异常:
node:events:353
throw er; // Unhandled 'error' event
^
TypeError: user.pull is not a function对如何让它工作有什么建议吗?
完整的JS代码:
const deleteMessage = (userID) => {
console.log('userID delete : ' +userID)
//Delete message collection corresponding to the userID
Message.findByIdAndDelete({_id:userID}).catch((err) => { console.log(err.message);});
//Delete messages corresponding to the userID from the receiver' message list
Message.find({users:{$elemMatch:{ _id:userID}}}, (err,doc)=>{
console.log(doc);
doc.forEach((user)=> {
user.pull({_id:userID})
doc.save();
})
}).catch((err) => {
console.log(err.message);
});
}消息架构:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const contentSchema = new Schema(
{
isMy: Boolean,
message: String,
createdAt: Date,
}
);
const receiverSchema = new Schema({
_id: String,
messages: [contentSchema],
});
const messageSchema = new Schema({
_id: String,
users: [receiverSchema],
});
module.exports = mongoose.model("Message", messageSchema);发布于 2021-06-13 18:48:03
你不能直接在集合上使用拉取,假设用户是你的集合,你可以像下面这样使用:
user.findOneAndUpdate({_id: userId}, { //here find that user
$pull: {_id: userId} //use your reference like message id or something
})如果你想要更清楚,请告诉我。谢谢。
https://stackoverflow.com/questions/67956969
复制相似问题