【问题标题】:Nodejs + MongoDB how to restrict data for specific userNodejs + MongoDB如何限制特定用户的数据
【发布时间】:2017-04-20 18:53:33
【问题描述】:

我有一个新的 mongodb 架构

let TestTable = new Schema({
  Title: String,
  Content: String,
});

这是添加数据的post方法:

 api.post('/add',authenticate, (req, res) => {
    let NewTestTable = new TestTable ();
    NewTestTable.Title = req.body.Title;
    NewTestTable.save(err => {
        if (err) {res.send(err);}
        res.json({message: "Addig was sucessfully"});
    })

假设我已登录并且我有用户 ID 如何仅为特定用户添加此架构的新数据

当我创建一个 GET 方法时,我将只收到该用户的数据

获取:

 api.get('/', authenticate,(req, res) => {
    TestTable.find({}, (err, testtable) => {
        if (err) {res.send(err);}
        res.json(testtable);
    });

谢谢!

【问题讨论】:

  • 你能再解释一下吗?问题太混乱了。
  • 假设我有两个用户,他们都需要使用 testtable 模式向数据库添加新数据我想限制特定用户的数据,如果 user1 将创建一个 get 方法,他将只接收他添加的数据

标签: node.js mongodb schema


【解决方案1】:

您需要在您的 TestTable 架构中引用用户,因此您可以添加数据,在搜索数据时只需要获取带有您的 userId 条件的数据以进行更新,您可以使用特定的文档 ID您的 TestTable 架构。

例如:

let TestTable = new Schema({
  Title: String,
  Content: String,
userId:{type:Schema.ObjectId,ref:"userId",default:null},

});

【讨论】:

  • 哦,谢谢...但是当我制作发布方法时,我需要做什么? NewTestTable.userId=req.body.userId?
猜你喜欢
  • 1970-01-01
  • 2017-12-04
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 2020-09-12
  • 2018-11-11
  • 1970-01-01
相关资源
最近更新 更多