无法使用猫鼬更新Mlab文档的值,因此将其另存为“ __v”:0

时间:2019-01-13 07:07:35

标签: node.js angularjs mongoose mlab

我是node和mongoDb的新手, 我有一个mongo数据库帐户,在其中创建了一个名为“ dbTestData”的集合

My Mongo DB Screen Shot

我正在尝试使用node express猫鼬和express创建CRUD操作, 而且我正在使用邮差来获取更新和删除值到mlab数据库。

我的Get呼叫工作正常,但是当我尝试在Json中发布值时,

enter image description here

我收到成功消息,但是当我检查数据库时,它将另存为

{
    "_id": {
        "$oid": "5c3ad1c19bc5932f800d26f7"
    },
    "__v": 0
}

我的app.js

const express = require('express');

const bodyParser = require("body-parser");
const mongoose=require('mongoose');
const app = express();
const dbTestData=require('./models/post')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


mongoose.connect("mongodb://<userName>:<password>@ds221242.mlab.com:21242/kiitasklist").then(()=>{
  console.log("hello");
}).catch(
  ()=>{
    console.log("heee");
  });

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, PATCH, PUT,DELETE, OPTIONS"
    );
    next();
  });

  app.post("/api/posts", (req, res, next) => {
    const post = new dbTestData({
      id:req.body.id,
      name:req.body.name
    });
    post.save().then(documents=>{
      console.log(post);
      res.status(201).json({
        message: 'Post added successfully'
      });
    });
  });


app.get("/api/posts",(req,res,next)=>{
  dbTestData.find().then(documents=>{
  res.status(200).json({
    message:'Posts fetched successful',
    posts:documents
    });
});
});


app.put("/api/posts/:id",(req,res,next)=>{
  const post = new dbTestData({
    _id:req.body._id,
    name:req.body.name
  });
  dbTestData.updateOne({_id:req.params.id},post).then(result=>{
    res.status(200).json({message:"update successfully"});
  });
});

app.delete("/api/posts/:id",(req,res,next)=>{
  dbTestData.deleteOne({_id:req.params.id}).then(documents=>{
     res.status(200).json({
       message:'posts fetched successful',
       posts:documents
     });
   });
});

module.exports = app;

我的Server.js

const http = require('http');
const app = require('./api/app');

const port = process.env.PORT || 3000;

const server = http.createServer(app);

server.listen(port);

我创建了猫鼬模式的post.js

const mongoose=require('mongoose');

var Schema = mongoose.Schema; 
module.exports= mongoose.model("dbTestData", new Schema({}), "DbTestData"); 

获取和删除均有效, 但是发布和放置操作未正确进行,它在我的控制台中返回一条成功消息,但空值为

{
    "_id": {
        "$oid": "5c3ad1c19bc5932f800d26f7"
    },
    "__v": 0
}

在POST期间被保存,而在PUT期间没有任何反应。

1 个答案:

答案 0 :(得分:0)

要解决此帖子问题

var Schema = mongoose.Schema; 

PostSchema = new Schema({
 id:Number,
 name: String
});
// the compile the model using mongoos model function giving the schema u created
const Post = module.exports= mongoose.model("dbTestData", PostSchema, "DbTestData");

之后,在您的帖子要求中按以下步骤进行操作

//before posting you need to require the model first 
const Post = require('./models/post'); // your post.js
app.Post("/api/posts", (req, res, next) => {
    const post = new Post({
      id:req.body.id,
      name:req.body.name
    });
    post.save().then(documents=>{
      console.log(post);
      res.status(201).json({
        message: 'Post added successfully'
      });
    });
  });

确保正确创建/定义模式,以便使用它保存数据。 正确放置模式后,放置后的操作与您做的工作相同

,最后也尝试一下。确保您添加的拖曳线与我在您的情况下给出的完全相同,并且已将它们切换

// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());