0

我为 MERN 堆栈项目创建了一个 UserSchema,我想将文档嵌套在创建的用户中。当我注册用户时,我试图在嵌套文档中发布虚拟数据,只是为了查看它们是否会显示在 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,单击箭头时不显示任何对象 邮递员

4

1 回答 1

0

这是因为它等待的东西不是你通过的东西。当这样时,因为它不是正确的类型,所以不会将任何内容保存到数据库中,从 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);
于 2021-01-12T08:12:29.957 回答