【发布时间】: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