简体   繁体   English

mongoose.save() 不保存所有字段

[英]mongoose.save() not saving all fields

im new to node and express so this might not be clear我是 node 和 express 的新手,所以这可能不清楚

I am using mongodb to make a mini twitter clone.我正在使用 mongodb 制作迷你 twitter 克隆。 When you submit your tweet (called mew in my app) it makes a post request.当您提交推文(在我的应用程序中称为 mew)时,它会发出发布请求。 even though the data is getting saved, its only saving __v _id and the timestamps即使数据正在保存,它也只保存 __v _id 和时间戳

things I've tried我尝试过的事情

  1. emptying my collection清空我的收藏
  2. using longhand for setting types使用速记设置类型
  3. different browsers不同的浏览器
  4. removing timestamps删除时间戳
  5. XHR instead of fetch XHR 而不是 fetch

my code我的代码

backend:后端:

const express = require("express");
const cors = require("cors");
const { log } = console;
const mongoose = require("mongoose");
const app = express();
app.use(cors());
app.use(express.json());

const uri =
  "mongodb+srv://***:***@twitter-ci8qa.gcp.mongodb.net/twitter?retryWrites=true&w=majority";
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
var Schema = mongoose.Schema;

var postSchema = new Schema(
  {
    name: String,
    content: String,
  },
  {
    timestamps: true,
  }
);
var p = [];
var Post = mongoose.model("Post", postSchema);
const { connection } = mongoose;
connection.on("open", () => log("MongoDB: Connected"));
function isValidMew(mew) {
  return (
    mew.name &&
    mew.name.toString().trim() !== "" &&
    mew.content &&
    mew.content.toString().trim !== ""
  );
}

app.get("/", (req, res) => {
  Post.find().then((p) => {
    old = p;
    res.json(p);
  });
});
app.post("/mews", (req, res) => {
  if (isValidMew(req.body)) {
    const newMew = {
      name: req.body.name.toString(),
      content: req.body.content.toString(),
    };
    p = [...p, newMew];
    log(p);
    var postCollection = new Post(p);
    postCollection.markModified("twitter.posts");
    postCollection.save((err) => {
      if (err) {
        log(err);
      } else {
        console.log("worked");
      }
    });
  } else {
    res.status(500);
    res.json({
      err: "invalid request",
    });
  }
});
app.listen(7777, () => {
  log("listening");
});

frontend:前端:

const form = document.querySelector(".form");
const loading = document.querySelector(".loading");
const API_URL = "http://localhost:7777/mews";
loading.style.display = "none";
form.addEventListener("submit", (e) => {
  e.preventDefault();
  const formdata = new FormData(form);
  const name = formdata.get("name");
  const content = formdata.get("content");
  const mew = {
    name,
    content,
  };
  loading.style.display = "";
  form.style.display = "none";
  fetch(API_URL, {
    method: "POST",
    body: JSON.stringify(mew),
    headers: {
      "content-type": "application/json",
    },
  });

  fetch("http://localhost:7777/")
    .then((res) => res.json())
    .then((data) => alert(JSON.stringify(data)));
  form.style.display = "initial";
  loading.style.display = "none";
});

The problem is that you are not passing a new Post -object to the Post -Model inside the /mews -handler, but instead you are passing an array as you're spreading the p -array together with newMew and thus creating a new array.问题是您没有将新的Post对象传递给/mews mews 处理程序中的Post模型,而是在将p数组与newMew一起传播时传递了一个数组,从而创建了一个新数组. So changing this to:因此将其更改为:

...
const newMew = {
      name: req.body.name.toString(),
      content: req.body.content.toString(),
    };
   
log(newMew);
const postCollection = new Post(newMew);
...

should fix the problem.应该解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM