【问题标题】:Reflecting Changes To Mongo DB After New Post Request - Mongoose & Nodejs在新的发布请求后反映对 Mongo DB 的更改 - Mongoose 和 Nodejs
【发布时间】:2020-08-23 10:00:13
【问题描述】:

对不起,我什至很难正确地提出问题。希望不要太混乱。

我正在我的 Mongo DB Atlas 中建立一对多关系。我正在使用猫鼬和 Nodejs。

我正在尝试为多个条目创建一个用户。现在让我们说它是一对一的,以消除一层复杂性。一个用户到一个条目。

后端中的所有代码都有效,但简而言之,我遇到的问题就是这样。 每当我发出创建新条目的发布请求时,我都可以在请求中包含该条目所属的用户 ID。但是,每当我发出创建新用户的发布请求时,我都不能在请求中包含条目 ID,因为该用户尚不存在任何请求。当我创建一个新条目时,mongo db 不会自动更新文档,以将该新条目添加到与其关联的用户。而且我不知道我需要做什么才能让它动态更新用户以包含属于他们的新条目。

这是我的用户和条目的模型/模式,因此您可以看到关联。

用户架构

 const mongoose = require('mongoose');

 const userSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  email: {type: String,
  required: true,
  unique: true,
  displayName: String,
  password: {type: String, required: true},
  entry: {type: mongoose.Schema.Types.ObjectId, ref: 'Entry', required: true}
}, {collection: "users"});

module.exports = mongoose.model("User", userSchema);

入口模式

 const mongoose = require('mongoose');

 const entrySchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  title: {type:String},
  body: {type:String, required: true},
  user: {type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
  entryImage: {type: String}
  }, {collection: 'entries'});

  module.exports = mongoose.model('Entry', entrySchema);

这是我的用户和条目路线。你可以看到我是如何为关联设置逻辑的

用户路线

 const express = require('express');
 const router = express.Router();
 const mongoose = require('mongoose');
 const User = require('../models/user');
 const bcrypt = require('bcrypt');
 const jwt = require('jsonwebtoken');

 router.get('/:userId', (req, res, next) => {
  const id = req.params.userId;

  User.findById(id)
   .select("_id email displayName password entries")
   .populate('entry')
   .exec()
   .then(user => {
      res.status(200).json({
       id: user._id,
       email: user.email,
       password: user.password,
       entry: user.entry
     })
    })
   .catch(err => {
     error: err
     })
   })


   router.post('/signup', (req, res, next) => {

    User.find({email: req.body.email})
     .exec()
     .then(user => {
       if(user.length >= 1){
      return res.status(422).json({
        message: "Username already exists!"
      }); 
    } else {
      bcrypt.hash(req.body.password, 10, (err, hash) => {
        if(err){
           return res.status(500).json({
           error: err
          }); 
        } else {
          const user = new User({
           _id: new mongoose.Types.ObjectId(),
           email: req.body.email,
           displayName: req.body.displayName,
           password: hash
         }); 

         user.save()
          .then(data => {
            res.status(201).json({
              message: "Your user information has been saved in our records",
              id: data._id,
              email: data.email,
              displayName: data.displayName
            })
          })
          .catch(err => {
            res.status(500).json({
              error: err
            })
           }) 
          }
         }) 
        } 
 })
 .catch(err => {
    res.status(500).json({error : err})
  })
 }); //End of signup post request

参赛作品请求示例

用户发布请求示例

如果您有任何其他问题,请告诉我。非常感谢,提前!

【问题讨论】:

    标签: javascript node.js mongodb rest mongoose


    【解决方案1】:

    问题出在您的架构中。您明确指定了 _id 字段。 您当前的方案不允许 mongoose 自动创建此 id。

    嗯,有两种选择:

    1. 最简单的方法。只需从架构中删除 _id 字段。 Mongoose 会在每个创建请求中自动为您生成这个。

    2. 如果你想指定这个,传递一个选项给 mongoose 以便它可以为你自动生成这个

    const userSchema = mongoose.Schema({
      _id: { type: Schema.ObjectId, auto: true },
    })
    

    【讨论】:

    • 谢谢。我删除了 id 逻辑,它仍然有效。所以你是对的。我仍然无法自动更新用户,但是我发现了猫鼬钩子,比如 pre 和 post。而且我听说这些钩子能够动态更新数据库。我会检查他们。再次感谢您
    • 要更新用户,您需要在更新调用中传递记录的_id
    猜你喜欢
    • 2016-04-07
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多