我试图找出一个聊天室与两个业主(发送者和接收者)从DB。如果没有这样的聊天室,就必须使用提供的is和名称创建聊天室。
我正在尝试创建一个用户登录和db存储的聊天应用程序。
//Mongoose Schema
const chatRoomSchema = new mongoose.Schema({
room:{
type: String,
trim:true,
required:true
},
owners:[{
owner:{
type:mongoose.Schema.Types.ObjectId,
required:true,
ref:'User'
}
}]
},{
timestamps:true
})
const ChatRoom = mongoose.model('Chatroom',chatRoomSchema)
//what i tried
const id1 = req.params.id1
const id2 = req.params.id2
let chatroom = ChatRoom.find({owners:{$all:[{owner:id1}, {owner:id2}]}})
if(!chatroom){
console.log('no chat room')
chatroom = new ChatRoom({room:'123', owners:[{owner:id1},{owner:id2}]})//creating a new chatroom
chatroom.save()
res.send(chatroom)
}我想找个聊天室,里面有两个主人的身份证。如果没有这样的聊天室,我们必须创建一个拥有两个ids的聊天室。
发布于 2019-09-01 15:01:56
owners:[{
owner:{
type:mongoose.Schema.Types.ObjectId,
required:true,
ref:'User'
}
}]至
owners:[{
type:mongoose.Schema.Types.ObjectId,
required:true,
ref:'User'
}]var arr = ['5d6bd3b374068124c461975a', '5d6bd3b374068124c4619759']
ChatRoom.find({owners:{$all:arr}}, (err, room) =>{...}全样本项目:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const init = false
mongoose.connect('mongodb://127.0.0.1/stackoverflow_play5')
//Mongoose Schema
const userSchema = new Schema({
username: String
})
const chatRoomSchema = new mongoose.Schema({
room:{
type: String,
trim:true,
required:true
},
owners:[{
type:mongoose.Schema.Types.ObjectId,
required:true,
ref:'User'
}]
},{
timestamps:true
})
const ChatRoom = mongoose.model('Chatroom',chatRoomSchema)
const User = mongoose.model('User',userSchema)
if(init){
User.insertMany([{username: 'yaya'}, {username: 'hoho'}, {username: 'mil'}], (err, users) => {
ChatRoom.insertMany([{room: 'r1', owners: [users[0]._id, users[1]._id]}], (err, chatrooms) => console.log('done.'))
})
}else{
//ChatRoom.find({}, (err, users)=>{console.log(users)})
var arr = ['5d6bdfe9c0d0af00ec68932c', '5d6bdfe9c0d0af00ec68932d']
ChatRoom.find({owners:{$all:arr}}, (err, room) =>{
console.log(room)
})
}发布于 2019-09-01 10:11:05
您可以将空间更改为由mongoo自动生成,而不是find然后创建,如果找不到,则可以使用findOneAndUpdate
const chatRoomSchema = new mongoose.Schema({
room:{
type: mongoose.Schema.Types.ObjectId,
auto: true
},
owners:[{
owner:{
type:mongoose.Schema.Types.ObjectId,
required:true,
ref:'User'
}
}]
},{
timestamps:true
})
const ChatRoom = mongoose.model('Chatroom',chatRoomSchema)
//what i tried
const id1 = req.params.id1
const id2 = req.params.id2
const options = { upsert: true, new: true, setDefaultsOnInsert: true };
let chatroom = ChatRoom.findOneAndUpdate(
{owners:{$all:[{owner:id1}, {owner:id2}]}},
{ owners:[{owner:id1},{owner:id2}] } ,
options, function(error, result) {
if (error) return;
// do something with the document
});https://stackoverflow.com/questions/57744911
复制相似问题