如何修复.save不是NodeJs中猫鼬的功能

时间:2019-03-17 04:04:51

标签: node.js

我正在编写一小段MEAN堆栈代码,该代码在mongo数据库中添加了一个帖子。我创建了架构,当我尝试在帖子中使用.save()时,会引发错误

  

post.save不是函数

这是我的模式

const mongoose =  require('mongoose');

const postSchema = {
    title : {type :String, require : true},
    content : {type : String, default :'No Content'}
}

module.exports=mongoose.model('Post',postSchema);

这是我的app.js

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');


const app = express();


mongoose.connect('mongodb+srv://venkatmokka:z0L7qSALBehoNPlT@cluster0-vr2p5.mongodb.net/mean-stack?retryWrites=true',{ useNewUrlParser: true })
    .then(()=>{
        console.log('Connected successfully');
    })
    .catch(()=>{
        console.log('Connection failed');
    });
app.use(bodyParser.json());

app.use((req,res,next)=>{
    res.setHeader('Access-Control-Allow-Origin','*');
    res.setHeader('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept');
    res.setHeader('Access-Control-Allow-Methods','GET,POST,DELETE,OPTIONS');
    next();
});

app.post('/api/posts',(req,res,next)=>{
    const post = req.body;
    console.log(post);

    // Save code that's throwing an error
    post.save();

    res.status(201).json({
        message : 'Post Added Successfully..!!!'
    });
});

app.get('/api/posts',(req,res,next)=>{

    posts = [{id:'1',title:'Post1',content:'This is post1'},
            {id:'2',title:'Post2',content:'This is post2'}
            ];
res.json({
    message : 'posts fetched successfully..!!',
    posts : posts
});
});


module.exports = app;

这是我的server.js

  const app = require("./backend/app");
  const debug = require("debug")("node-angular");
  const http = require("http");

  const normalizePort = val => {
    var port = parseInt(val, 10);

    if (isNaN(port)) {
      // named pipe
      return val;
    }

    if (port >= 0) {
      // port number
      return port;
    }

    return false;
  };

  const onError = error => {
    if (error.syscall !== "listen") {
      throw error;
    }
    const bind = typeof port === "string" ? "pipe " + port : "port " + port;
    switch (error.code) {
      case "EACCES":
        console.error(bind + " requires elevated privileges");
        process.exit(1);
        break;
      case "EADDRINUSE":
        console.error(bind + " is already in use");
        process.exit(1);
        break;
      default:
        throw error;
    }
  };

  const onListening = () => {
    const addr = server.address();
    const bind = typeof port === "string" ? "pipe " + port : "port " + port;
    debug("Listening on " + bind);
  };

  const port = normalizePort(process.env.PORT || "3000");
  app.set("port", port);

  const server = http.createServer(app);
  server.on("error", onError);
  server.on("listening", onListening);
  server.listen(port);

当我尝试不使用.save()函数时。帖子已成功从服务器获取到角侧,并显示在其他组件中(创建该组件可显示输入的帖子。但是,在使用save方法时,甚至不会从服务器端显示帖子)。

1 个答案:

答案 0 :(得分:2)

您需要创建一个新的Post Model来调用函数保存。可以找到文档here

app.post('/api/posts',(req,res,next)=>{
  const post = req.body;
  console.log(post);

  var postModel = new Post(post);
  postModel.save(function (err, newPost) {
    if (err) {
    } else {
      //Save ok
      res.status(201).json({
        message : 'Post Added Successfully..!!!'
      });
    }
  });
});