I'm having an issue in my NodeJs API and Mongo where I have to Post and Populate with the Username string the field Username.
When I post I get this error:
"TypeError: newPost.save(...).populate is not a function"
Post model:
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;
This is where I'm doing the post method:
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);
}
});
The response output how should be:
{
"_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
}
I will be also glad to know if the idea of the route like that has sense as the post need to have username if better to have it in the body or in params the request.