我的嵌套文档没有显示,Mongoose,Express
My nested document does not show up, Mongoose, Express
我为 MERN 堆栈项目创建了一个 UserSchema,我想在创建的用户中嵌套文档。当我注册用户时,我尝试 post 嵌套文档中的虚拟数据,只是为了查看它们是否会显示在 MongoDB Atlas 和 Postman 中,但是当我单击数组时,它甚至在数组中什么也没有显示虽然我放了资料。
这是我的代码
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ClassworkSchema = new Schema({
name: String,
time: Date,
todo: String,
isDone: false
});
const OutcomesSchema = new Schema({
name: String,
time: Date,
todo: String,
isDone: false,
isApproved: false
})
const MeetupSchema = new Schema({
name: String,
time: Date,
location: String,
attended: false
})
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
classwork: [ClassworkSchema],
outcomes: [OutcomesSchema],
meetups: [MeetupSchema],
});
// const UserSchema = new Schema({
// name: {type: String, required: true},
// email: {type: String, required: true},
// password: {type: String, required: true},
// date: {type: Date, default: Date.now},
// })
module.exports= User = mongoose.model('users', UserSchema);
控制器
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require ("jsonwebtoken");
const keys = require("../../config/key");
const validateRegisterInput = require("../../validation/register");
const validateLoginInput = require("../../validation/login");
const User = require("../../models/User");
router.post("/register", (req, res) => {
//FORM VALIDATION
const {errors, isValid } = validateRegisterInput(req.body)
//CHECK VALIDATION
if(!isValid) {
return res.status(400).json(errors)
}
User.findOne({ email: req.body.email }).then( returnedUser => {
if(returnedUser) {
return res.status(400).json({email: "Email already exists"});
}
});
// saving user with request information to database
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
bcrypt.genSalt(10, (err, salt)=>{
bcrypt.hash(newUser.password, salt, (err, hash)=>{
if(err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
});
router.post("/login", (req, res)=>{
const {errors, isValid} = validateLoginInput(req.body)
if(!isValid){
return res.status(400).json(errors)
}
const email = req.body.email;
const password = req.body.password
User.findOne({ email: email }).then(user =>{
if(!user){
return res.status(404).json({ emailNotFound: "Email not found"});
}
bcrypt.compare(password, user.password).then(isMatch => {
if(isMatch){
const payload = { id: user.id, name: user.name };
jwt.sign(payload,
keys.secretOrKey,
{expiresIn: 31556926},
(err, token) => {
res.json({ success: true, token: "Bearer " + token });
});
} else {
return res.status(400)
.json({passwordincorrect: "password incorrect"})
}
})
})
});
module.exports = router;
服务器
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const app = express();
const users = require("./controllers/api/users")
// const classwork = require("./controllers/api/classwork")
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
//DATA BASE CONFIGURATION
const dbkeys = require("./config/key").mongoURI;
mongoose.connect(
dbkeys,
{useNewUrlParser: true} )
.then(()=> console.log("database connection successful"))
.catch(err => console.log(err))
app.use(passport.initialize());
require("./config/passport")(passport);
app.use("/api/users", users);
// app.use("/api/classwork", classwork)
const port = 5000;
app.listen( port, () => console.log("server us up and running on port 5000!"))
mongodb atlas, no object shows when the arrow is clicked
Postman
这是因为它等待的不是你传递的东西。当因为类型不正确而不会将任何内容保存到数据库时,从 mongoose 文档中应该这样写:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var PersonSchema = new Schema({
name : String
, age : Number
, stories : [{ type: Schema.ObjectId, ref: 'Story' }]
});
var StorySchema = new Schema({
_creator : { type: Schema.ObjectId, ref: 'Person' }
, title : String
, fans : [{ type: Schema.ObjectId, ref: 'Person' }]
});
var Story = mongoose.model('Story', StorySchema);
var Person = mongoose.model('Person', PersonSchema);
我为 MERN 堆栈项目创建了一个 UserSchema,我想在创建的用户中嵌套文档。当我注册用户时,我尝试 post 嵌套文档中的虚拟数据,只是为了查看它们是否会显示在 MongoDB Atlas 和 Postman 中,但是当我单击数组时,它甚至在数组中什么也没有显示虽然我放了资料。
这是我的代码
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ClassworkSchema = new Schema({
name: String,
time: Date,
todo: String,
isDone: false
});
const OutcomesSchema = new Schema({
name: String,
time: Date,
todo: String,
isDone: false,
isApproved: false
})
const MeetupSchema = new Schema({
name: String,
time: Date,
location: String,
attended: false
})
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
classwork: [ClassworkSchema],
outcomes: [OutcomesSchema],
meetups: [MeetupSchema],
});
// const UserSchema = new Schema({
// name: {type: String, required: true},
// email: {type: String, required: true},
// password: {type: String, required: true},
// date: {type: Date, default: Date.now},
// })
module.exports= User = mongoose.model('users', UserSchema);
控制器
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require ("jsonwebtoken");
const keys = require("../../config/key");
const validateRegisterInput = require("../../validation/register");
const validateLoginInput = require("../../validation/login");
const User = require("../../models/User");
router.post("/register", (req, res) => {
//FORM VALIDATION
const {errors, isValid } = validateRegisterInput(req.body)
//CHECK VALIDATION
if(!isValid) {
return res.status(400).json(errors)
}
User.findOne({ email: req.body.email }).then( returnedUser => {
if(returnedUser) {
return res.status(400).json({email: "Email already exists"});
}
});
// saving user with request information to database
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
bcrypt.genSalt(10, (err, salt)=>{
bcrypt.hash(newUser.password, salt, (err, hash)=>{
if(err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
});
router.post("/login", (req, res)=>{
const {errors, isValid} = validateLoginInput(req.body)
if(!isValid){
return res.status(400).json(errors)
}
const email = req.body.email;
const password = req.body.password
User.findOne({ email: email }).then(user =>{
if(!user){
return res.status(404).json({ emailNotFound: "Email not found"});
}
bcrypt.compare(password, user.password).then(isMatch => {
if(isMatch){
const payload = { id: user.id, name: user.name };
jwt.sign(payload,
keys.secretOrKey,
{expiresIn: 31556926},
(err, token) => {
res.json({ success: true, token: "Bearer " + token });
});
} else {
return res.status(400)
.json({passwordincorrect: "password incorrect"})
}
})
})
});
module.exports = router;
服务器
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const app = express();
const users = require("./controllers/api/users")
// const classwork = require("./controllers/api/classwork")
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
//DATA BASE CONFIGURATION
const dbkeys = require("./config/key").mongoURI;
mongoose.connect(
dbkeys,
{useNewUrlParser: true} )
.then(()=> console.log("database connection successful"))
.catch(err => console.log(err))
app.use(passport.initialize());
require("./config/passport")(passport);
app.use("/api/users", users);
// app.use("/api/classwork", classwork)
const port = 5000;
app.listen( port, () => console.log("server us up and running on port 5000!"))
mongodb atlas, no object shows when the arrow is clicked Postman
这是因为它等待的不是你传递的东西。当因为类型不正确而不会将任何内容保存到数据库时,从 mongoose 文档中应该这样写:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var PersonSchema = new Schema({
name : String
, age : Number
, stories : [{ type: Schema.ObjectId, ref: 'Story' }]
});
var StorySchema = new Schema({
_creator : { type: Schema.ObjectId, ref: 'Person' }
, title : String
, fans : [{ type: Schema.ObjectId, ref: 'Person' }]
});
var Story = mongoose.model('Story', StorySchema);
var Person = mongoose.model('Person', PersonSchema);