我正在尝试创建群聊应用程序。但是当我将相同的id(字符串)放入数组时,唯一的true不起作用,并且相同的id被添加到数组中,我最终得到了这个例子。我希望userIds ID数组只包含唯一ID
。{ _id: 5885dc260a6bd22768bef387,
roomName: 'Room1',
author: '587cd401a279b834b0a4cb8d',
__v: 0,
messages: [],
usersIds:
[ 587cd401a279b834b0a4cb8d,
587cd3ed7bd35b37d4c75a36,
587cd3ed7bd35b37d4c75a36 ] }
这是我的房间架构
const roomChat = new Schema({
roomName: String,
author: String,
usersIds:[
{
type: Schema.ObjectId,
unique: true
}
],
messages: [
{
author: String,
text: String,
date: Number
}
]
});
这就是我在特定房间中将用户添加到userIds的方式
app.put('/roomChat', (req, res) => {
GroupChat.findByIdAndUpdate(req.body.roomId, {$push:{usersIds:req.body.userId}},{safe: true},(err,room) => {
console.log(room);
});
});
答案 0 :(得分:2)
只需使用$addToSet
代替$push
app.put('/roomChat', (req, res) => {
GroupChat.findByIdAndUpdate(req.body.roomId, {$addToSet:{usersIds:req.body.userId}},{safe: true, new:true},(err,room) => {
console.log(room);
});
});