【发布时间】:2020-05-08 13:56:30
【问题描述】:
我在我的 NodeJs API 和 Mongo 中遇到问题,我必须使用用户名字符串在字段用户名中发布和填充。
当我发布时,我收到此错误:
“TypeError: newPost.save(...).populate 不是函数”
后模型:
const mongoose = require("mongoose");
const schema = {
text: {
type: String,
required: true,
unique: true
},
username: {
type: mongoose.Schema.Types.String,
ref: "Profile",
required: true
},
image: {
type: String,
default: "https://via.placeholder.com/150",
required: false
},
createdAt: {
type: Date,
default: Date.now,
required: false
},
updatedAt: {
type: Date,
default: Date.now,
required: false
}
};
const collectionName = "posts";
const postSchema = mongoose.Schema(schema);
const Post = mongoose.model(collectionName, postSchema);
module.exports = Post;
这是我在做 post 方法的地方:
postRouter.post("/", async (req, res) => {
try {
const newPost = await Posts.create(req.body);
const username = await Profiles.findOne({
username: req.body.username
});
if (!username) res.status(400).send("Username not found");
newPost.save().populate(username.username);
res.send({ success: "Post added", newPost });
} catch (error) {
res.status(500).send(error);
console.log(error);
}
});
响应输出应该如何:
{
"_id": "5d93ac84b86e220017e76ae1", //server generated
"text": "this is a text 12312 1 3 1", <<--- THIS IS THE ONLY ONE SENDING"
"username": "admin",<-- FROM REQ.body or params ???
"createdAt": "2019-10-01T19:44:04.496Z", //server generated
"updatedAt": "2019-10-01T19:44:04.496Z", //server generated
"image": ... //server generated on upload, set a default here
}
我也很高兴知道这样的路线的想法是否有意义,因为帖子需要有用户名,如果最好将它放在正文或请求的参数中。
【问题讨论】:
-
检查这个mongoosejs.com/docs/populate.html你会更好地了解填充
-
这将是您的问题及其解决方案。 HELP