【问题标题】:how can i send the data of one route to an other route Mongodb-Nodejs如何将一条路由的数据发送到另一条路由 Mongodb-Nodejs
【发布时间】:2020-06-30 16:06:47
【问题描述】:

我正在研究 MERN 应用程序,我对后端有疑问!我有 2 个模型用户和管理员,我希望将用户的数据发送给管理员,并且管理员可以管理任何用户(更新、删除、添加)

问题是我正在处理两条不同的路线(用户和管理员),我无法将用户的数据发送到管理员的数据

所以这是用户的架构

 const mongoose = require("mongoose");
    const Schema = mongoose.Schema;
    // Create Schema
    const UserSchema = new Schema({
      username: {
        type: String,
        required: true
      },
      email: {
        type: String,
        required: true
      },
      password: {
        type: String,
        required: true
      },
      date: {
        type: Date,
        default: Date.now
      },
      birthdate:{
        type: Date
      },
     
      age:{
        type: Number,
     
      pictureID: { type: mongoose.Schema.ObjectId, ref: "pictures"},
      following: [{type: mongoose.Schema.ObjectId, ref: 'User'}],
      followers: [{type: mongoose.Schema.ObjectId, ref: 'User'}]
    });
    module.exports = User = mongoose.model("users", UserSchema);

这是管理员的架构

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const AdminSchema = new Schema({
  username: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  },
  birthdate:{
    type: Date
  },
  age:{
    type: Number,
  },
  pictureID: { type: mongoose.Schema.ObjectId, ref: "pictures"},
  developers: [{type: mongoose.Schema.ObjectId, ref: 'User'}],
  testers: [{type: mongoose.Schema.ObjectId, ref: 'User'}]
});
module.exports = Admin = mongoose.model("admins", AdminSchema);

【问题讨论】:

  • “你不能将用户的数据发送到管理员数据”是什么意思?
  • 如果一个开发人员创建了一个我想要发送给管理员的新帐户,我的意思是它将被推送到管理员的“开发人员”数组中!因此管理员可以获取所有开发人员和测试人员并管理他们!

标签: node.js mongodb mern


【解决方案1】:

创建新用户后,您可以更新管理员的开发人员/测试人员字段。

const admin = await Admin.find({});// find the admin
admin.developers.push(user); //user that you just created
admin.save((result)=>{
    console.log(result);
});

【讨论】:

  • 我必须在路由管理员中编写此代码吗?还是用户? !
  • 用户路由。虽然我不确定您为什么要将用户的引用保存在管理架构中。我真的不明白这背后的目的。
  • 管理员必须有权访问所有用户(开发人员和测试人员),他可以获取所有用户的帐户,删除他们的帐户/他可以禁止他们的帐户!
  • 在admin路由中,可以查看访问该路由的用户是否为admin。如果她/他是管理员,那么您可以很容易地找到/删除文档。例如User.findOneAndRemove({_id: userId})User.findOneAndUpdate({_id: userId},{$set:{name:'newName'}})
  • 好吧,我试图让管理员有权删除这样的用户 router.route('/delete/:id').delete(function(req, res) { User.findByIdAndRemove(req.body.id, function (err, user){ if (err) return next(err); res.send('Deleted successfully!'); }); }); 它显示我已成功删除,但是当我找到用户时,它仍然存在于用户的数据中
【解决方案2】:

Function register 这是路由用户中的功能寄存器!我添加了推送,但它给出了错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-27
    • 2019-09-22
    • 2020-11-26
    • 2018-01-06
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    相关资源
    最近更新 更多