[英]mongoose.save() not saving all fields
我是 node 和 express 的新手,所以這可能不清楚
我正在使用 mongodb 制作迷你 twitter 克隆。 當您提交推文(在我的應用程序中稱為 mew)時,它會發出發布請求。 即使數據正在保存,它也只保存 __v _id 和時間戳
我嘗試過的事情
我的代碼
后端:
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");
});
前端:
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";
});
問題是您沒有將新的Post
對象傳遞給/mews
mews 處理程序中的Post
模型,而是在將p
數組與newMew
一起傳播時傳遞了一個數組,從而創建了一個新數組. 因此將其更改為:
...
const newMew = {
name: req.body.name.toString(),
content: req.body.content.toString(),
};
log(newMew);
const postCollection = new Post(newMew);
...
應該解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.