猫鼬只会拯救' _v'和' _id'

时间:2017-12-03 09:01:58

标签: javascript node.js mongodb express mongoose

我试图将书添加到MongoDB并尝试使用Postman发布它只保存_id和_v。我在这里读了很多答案,但都没有用。让书籍运作良好但我从命令提示符中插入了一本书。 还有其他方法可以保存吗?

以下是api.js文件的代码:



onst express = require('express');
const router = express.Router();
const mongoose = require('mongoose');

var Book = require('../models/book');

//MONGODB CONNECTION
mongoose.connect('mongodb://127.0.0.1:27017/books' ,({useMongoClient: true}));

mongoose.connection.on('connected', () => {
        console.log('Successfully connected to MongoDB');
});

mongoose.connection.once('error', (err) =>{
        console.log('Error: '+ err);
});

//Get books
router.get('/books', function(req, res) {
  Book.find(function(err, books) {
      if (err) {
          res.send(err);
         } else 
      res.json(books); 
  });
});

//Post books
router.post('/books', (req,res) => {
    let newBook = new Book (req.body);
      newBook.name = req.body.name,
      newBook.author = req.body.author,
      newBook.pages = req.body.pages,
      newBook.save((err, newBook) => {
        if (err){
          console.log(err);
        } else {
          res.json(newBook);
        }
      });
});

module.exports = router;




以下是模型文件的代码:



const mongoose = require('mongoose');
var schema = mongoose.Schema;

var bookSchema = new schema ({
    name: String,
    author: String,
    pages: Number
});

module.exports = mongoose.model('book', bookSchema, 'books');




服务器文件的代码:



const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const api = require('./server/routes/api');

const app = express();


//SERVER 

const port = 3000;


app.listen(3000, () => {
    console.log('Server started on port '+port)
});

// BODYPARSER

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

//API

app.use('/api', api);


// ROUTES

app.use(express.static(path.join(__dirname, 'dist')));

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
  });




0 个答案:

没有答案