【问题标题】:Data fetching from Atlas Mongo with mongoose to angular app使用 mongoose 从 Atlas Mongodb 获取数据到 Angular 应用程序
【发布时间】:2020-08-24 02:08:06
【问题描述】:

我在我的注册页面中添加了一个新输入,即名称字段,并且也更改了架构中的设置。现在我如何获取该名称以在我的 post-list 组件和 post-create 组件中使用?

这是创建用户的语法。现在我想在帖子标题的地方使用这个名字。

{

  _id: 5eb54bb209a6c405e5fb5b97,

  name: 'chokko',

  email: 'chokko@test',

  password: '********************************'

}

createUser.js

exports.createUser = (req, res, next) => {
  bcrypt.hash(req.body.password, 10).then((hash) => {
    const user = new User({
      name: req.body.name,
      email: req.body.email,
      password: hash,
    });
    user
      .save()
      .then((result) => {
        res.status(201).json({ message: "User created!", result: result });
      })
      .catch((err) => {
        res
          .status(500)
          .json({ message: "Invalid authentication credentials!" });
      });
  });
};

【问题讨论】:

  • 请添加一些最低限度的可重现代码或您的尝试 - 谢谢
  • exports.createUser = (req, res, next) => { bcrypt.hash(req.body.password, 10).then((hash) => { const user = new User({名称:req.body.name,电子邮件:req.body.email,密码:哈希,});用户 .save() .then((result) => { res.status(201).json({ message:"用户创建!", result: result, }); }) .catch((err) => { res .status(500) .json({ message: "Invalid authentication credentials!" }); }); }); };
  • 编辑你的问题而不是评论

标签: node.js angular mongodb mongoose mongodb-atlas


【解决方案1】:

您可以使用 Model.findById() 来获取特定文档,并使用“投影”来选择字段(在本例中为“名称”字段)。

User.findById(id,'-id name')

此外,您必须明确删除 _id ('-id'),除非您希望它与选定的字段一起返回。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-25
    • 2019-09-04
    • 2012-02-12
    • 1970-01-01
    • 2013-11-06
    • 2019-12-22
    • 2020-02-22
    相关资源
    最近更新 更多