【发布时间】:2020-07-08 13:25:55
【问题描述】:
我有一个简单的 twitter 应用程序的架构
const userSchema = new Schema ({
loginInfo: {
username: String,
email: String,
password: String
},
tweets: [{
content: String,
likes: Number,
comments: [{
owner: String,
content: String,
likes: Number
}]
}],
followers: [String],
following: [String]
})
我想让端点只返回具有相同 _id 的推文,该推文已作为 URL 上的参数给出.. 我在下面制作了该解决方案并且它工作正常,但我相信有比这更好的解决方案..
const handleTweet = (User) => (req,res) => {
const { id } = req.params;
let theTweet = [];
User.findOne({ "tweets._id": id})
.then(user => {
user.tweets.forEach(tweet => {
if(tweet._id.toString() === id)
return theTweet.push(tweet)
})
res.json(theTweet)
})
.catch(err => res.json(err))
}
module.exports = handleTweet;
还有一个问题:最好是制作这样的嵌套架构还是为每个架构制作不同的模型(在这种情况下,用户的架构和推文的另一个架构)?
【问题讨论】:
标签: node.js mongodb model schema