【发布时间】:2017-01-08 04:40:10
【问题描述】:
我是 Mongo/Mongoose 的新手,无法执行以下操作:
我正在创建一个简单的应用程序,它利用 Yelp API 来查找用户可以搜索的区域周围的夜总会/酒吧。
用户会看到一个俱乐部列表,每个列表都有一个发送到 mongodb 的表单,该表单可以跟踪为该特定俱乐部保留的其他用户。
我已经制作了Clubs 的架构
const clubSchema = new Schema({
clubID: String,
guests: [String]
})
其中 clubID 是俱乐部的 ID,guests 只是一个用于跟踪用户名的字符串数组。
我想做以下事情:
1) 当特定的clubID在数据库中不存在时,它会创建一个新的userName并将userName插入到guests中
2) 如果clubID 存在且userName 在guests 中不存在(意味着它是不同的用户),它会将userName 推入guests 数组中
3) 如果clubID 存在并且userName 也存在于guests 中,则从guests 中删除该userName
我有以下伪代码:
exports.UpdateGuestList = function(req, res, next){
const clubID = req.params.clubID;
const userName = req.params.userName
const userEmail = req.params.userEmail;
Club.findOne({ clubID: clubID}, function(err, existingClub){
if (err) { return next(err) ;}
// if clubID exist in the data base, check the following
if (existingClub){
//1) if the current userName exist, remove it from guests array
if (existingClub.guests.includes(userName)){
console.log('Remove guest')
} else{ //2) if the current userName doesnt exist, push it into guests aaray
console.log('Push in gueest')
}
return res.send({"message": "done"})
}
// If clubID does not exist, create and save clubID
const club = new Club({
clubID: clubID,
guests: [userName]
})
club.save(function(err){
if (err) {return next(err)}
res.send({"message": "done"})
})
})
}
【问题讨论】:
-
你想要什么?
-
基本按照1)2)3)的逻辑进行
标签: javascript node.js mongodb mongoose mongoose-schema