簡體   English   中英

在新的發布請求后反映對 Mongo DB 的更改 - Mongoose & Nodejs

[英]Reflecting Changes To Mongo DB After New Post Request - Mongoose & Nodejs

對不起,我什至很難正確地提出問題。 希望它不會太混亂。

我正在我的 Mongo DB Atlas 中建立一對多關系。 我正在使用貓鼬和 Nodejs。

我正在嘗試為多個條目創建一個用戶。 現在讓我們說它是一對一的,以消除一層復雜性。 一個用戶對一個條目。

后端中的所有代碼都可以工作,但簡而言之,我遇到的問題是。 每當我提出創建新條目的發布請求時,我都可以在請求中包含該條目所屬的用戶 ID。 但是每當我發出創建新用戶的 post 請求時,我都無法在請求中包含條目 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

條目發布請求示例新條目后請求

用戶發布請求示例新用戶發布請求

請讓我知道您有任何其他問題。 非常感謝,提前!

問題出在您的架構中。 您明確指定了_id字段。 您當前的方案不允許貓鼬自動創建此 ID。

嗯,有兩種選擇:

  1. 最簡單的方法。 只需從您的架構中刪除_id字段。 Mongoose 會在每個創建請求中自動為你生成這個。

  2. 如果你想指定這個,傳遞一個選項給貓鼬,這樣它就可以為你自動生成這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM