How do I use populate with callbacks? - mongodb

User model
const Schema = mongoose.Schema
const userSchema = new Schema({
username: { type: String, required: true },
email: { type: String, reuired: true },
password: { type: String, required: true },
posts:[{ type: Schema.Types.ObjectId, ref: "Posts" }]
}, { timestamps: true })
Post model
const Schema = mongoose.Schema;
const postSchema = new Schema({
title: { type: String, required: true },
content: { type: String, required: true },
user: { type: Schema.Types.ObjectId, ref: "User" },
}, { timestamps: true }
endpoint for getting all posts with all users information
listPostsWithUsers: (req, res, next) => {
Post.find({}, (error, posts) => {
if (error) {
return res.status(500).json({ error: "something went wrong" })
} else if (!posts) {
return res.status(400).json({ msg: "sorry no posts" })
} else if (posts) {
return res.status(200).json({ posts })
}
})
}
The output should be the returned posts with the user object so that I can identify which post the user has posted.
Now, my question is how do I apply populate() method in the above endpoint. Mostly all examples are with exec() function but I've seen no example with callbacks. It's kind of a syntax problem.
Thank you.
Update#1: The result I'm getting currently.
{
"posts": [
{
"_id": "5e65cce5ebddec0c5cc925ab",
"title": "Neil's Post",
"content": "post by neil.",
"createdAt": "2020-03-09T04:58:13.900Z",
"updatedAt": "2020-03-09T04:58:13.900Z",
"__v": 0
},
{
"_id": "5e65cd32ebddec0c5cc925ad",
"title": "Slash's post",
"content": "post by slash.",
"createdAt": "2020-03-09T04:59:30.180Z",
"updatedAt": "2020-03-09T04:59:30.180Z",
"__v": 0
},
{
"_id": "5e65f430a989612916636e8d",
"title": "Jimmy's post",
"content": "post by jimmy",
"createdAt": "2020-03-09T07:45:52.664Z",
"updatedAt": "2020-03-09T07:45:52.664Z",
"__v": 0
}
]
}
Update#2
users collection.
{
"users": [
{
"posts": [],
"_id": "5e65ccbeebddec0c5cc925aa",
"username": "Neil",
"email": "neily888#gmail.com",
"password": "$2b$10$AHHRKuCX3nakMs8hdVj0DuwD5uL0/TJwkJyKZYR/TXPTrIo9f80IW",
"createdAt": "2020-03-09T04:57:35.008Z",
"updatedAt": "2020-03-09T04:57:35.008Z",
"__v": 0
},
{
"posts": [],
"_id": "5e65cd0eebddec0c5cc925ac",
"username": "Slash",
"email": "slash938#gmail.com",
"password": "$2b$10$QQX/CFJjmpGdBAEogQ4XO.1e1ZowuPCX7pJcHTUav7NfatGgp6sa6",
"createdAt": "2020-03-09T04:58:54.520Z",
"updatedAt": "2020-03-09T04:58:54.520Z",
"__v": 0
},
{
"posts": [],
"_id": "5e65f408a989612916636e8c",
"username": "Jimmy",
"email": "jimmy787#gmail.com",
"password": "$2b$10$/DjwWYIlNswgmYt3vo7hJeNupfBdFGe7p77uisYUViKv8IdhasDC.",
"createdAt": "2020-03-09T07:45:12.293Z",
"updatedAt": "2020-03-09T07:45:12.293Z",
"__v": 0
}
]
}
Update#3:
usersController
const User = require("../models/User")
module.exports = {
createUser: (req, res) => {
User.create(req.body, (err, createdUser) => {
if (err) console.log(err)
res.json({createdUser})
})
},
listUsers: (res) => {
User.find({}, (err, users) => {
if (err) console.log(err)
res.json({users})
})
},
getUser: (req, res) => {
User.findById(req.params.id, (err, user) => {
if (err) console.log(err)
return res.json({user})
})
},
updateUser: (req, res) => {
const user = {
username: req.body.username,
email: req.body.email,
password: req.body.password
}
User.findOneAndUpdate(req.params.id, user, { new: true }, (err, updatedUser) => {
if (err) console.log(err)
res.json({updatedUser})
})
},
deleteUser: (req, res) => {
User.findByIdAndDelete(req.params.id, (err, deleteduser) => {
if (err) console.log(err)
return res.status(200).json({ user: deleteduser })
})
}
}
postsController
const Post = require("../models/Post")
module.exports = {
createPost: (req, res) => {
const data = {
title: req.body.title,
description: req.body.description,
}
Post.create(data, (err, newPost) => {
if (err) console.log(err);
return res.status(200).json({ newPost })
})
},
listPosts: (res) => {
Post.find({}, async (err, posts) => {
if (err) console.log(err);
posts = await Post.populate(posts, {
path: "user",
model: "User"
})
return res.status(200).json({ posts })
})
},
findPost: (req, res) => {
Post.findById(req.params.id, (err, post) => {
if (err) console.log(err);
return res.json({ post })
}
)
},
updatePost: (req, res) => {
const post = {
title: req.body.title,
description: req.body.description
}
Post.findByIdAndUpdate(req.params.id, post, { new: true },(err, updatedPost) => {
if (err) console.log(err);
return res.status(200).json({ updatedPost })
})
},
deletePost: (req, res) => {
Post.findByIdAndDelete(req.params.id, (err, deletedPost) => {
if (err) console.log(err);
return res.status(200).json({ deletedPost })
})
}
}
Update#4
router.get("/posts/:id", usersController.getUserPosts) `
getUserPosts: (req, res) => {
User.findById(req.params.id, async (err, user) => {
if (err) {
return res.status(500).json({ error: "Server error" })
} else if (!user) {
return res.status(400).json({ error: "No user" })
} else if (user) {
user = await User.populate("user", {
path: "posts",
model: "Post"
})
return res.status(200).json({ user })
}
})
}

I suggest you to use mongoose populate.
listPostsWithUsers : (req, res, next) => {
Post.find({}).populate('user').exec(function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
})
}
You can refer this official mongoose populate document
You can even populate as many fields required by using populate as
populate([{ path: 'user' }, { path: 'book', select: { author: 1 } }])
with the help of select in populate, you can project the required fields (get only those fields from populated collection.)
Edit 1
createPost: (req, res) => {
const data = {
title: req.body.title,
description: req.body.description,
user: req.user._id,
}
Post.create(data, (err, newPost) => {
if (err) console.log(err);
return res.status(200).json({ newPost })
})
You will need to add user field in post while creating.
take user id from token or from query and you would be good to go.
Edit 2
getUserPosts: (req, res) => {
User.findById(req.params.id).populate([{ path: 'posts' }])
.exec(function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
}
You are finding data in user module and you want to populate post data, so you just need to say which field you want to populate as you have already defined on field which model to refer by adding ref with that field in mongoose schema.
getUserPosts: (req, res) => {
User.findById(req.params.id, async (err, user) => {
if (err) {
return res.status(500).json({ error: "Server error" })
} else if (!user) {
return res.status(400).json({ error: "No user" })
} else if (user) {
user = await User.populate("posts")
return res.status(200).json({ user })
}
})
}
This should also work for you.

You can do that after getting the posts as:
listPostsWithUsers: (req, res, next) => {
Post.find({}, async (error, posts) => {
if (error) {
return res.status(500).json({ error: "something went wrong" })
} else if (!posts) {
return res.status(400).json({ msg: "sorry no posts" })
} else if (posts) {
posts = await Post.populate(posts, {
path: 'user',
model: 'User'
});
return res.status(200).json({ posts })
}
})
}

Related

How change name of parameter on express response

I'm using mongoose and I would like that when I get all users send me uid instead of _id.
const allUssers = (req, res, next) => {
try {
User.find({})
.select("username")
.select("email")
.select("image")
.exec((err, users) => {
if (err) {
return res.status(400).json({
ok: false,
msg: "Error listing users",
});
}
return res.status(200).json({
ok: true,
users: users,
});
});
} catch (err) {
return res.status(500).json({
ok: false,
msg: "Please contact with administrator",
});
}
};
You can update your schema to use an alias:
let User = new Schema({
_id: { type: String, alias: "uid" }
});
Or you can map your users to something different:
return res.status(200).json({
ok: true,
users: users.map(({ _id, ...user }) => ({ uid: _id, ...user }),
});

Updating array of objects in Mongoose

I can't handle updating array of objects in my database, tried many options but nothing worked. Im pretty sure that the answer is obvious, but I couldn't manage it since wednesday.
Here is my kitSchema:
const kitSchema = new mongoose.Schema({
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
kit: {
type: Array,
required: true,
},
profiles: {
type: Array,
required: true,
},
});
module.exports = mongoose.model("Kit", kitSchema);
All users have their own document, and there are also profiles in it. I want to update single profile by passing the id of user and id of profile.
Example of data:
_id: 1,
email: "abc#mail",
password: "abc",
profiles: [
{
id: 1,
name: John
},
]
And here's my latest solution which doesn't work:
router.put("/profile/:id", async (req, res) => {
let kit = await Kit.findById(req.params.id, (error, data) => {
if (error) {
console.log(error);
} else {
console.log(data);
}
});
try {
await kit.profiles.findOneAndUpdate(
{ id: req.body.id },
{ name: req.body.name },
{ new: true },
(error, data) => {
if (error) {
console.log(error);
} else {
console.log(data);
}
}
);
try {
res.status(202).json({ message: "Changed" });
} catch (err) {
res.status(400).json({ message: err });
}
} catch (err) {
res.status(400).json({ message: err });
}
});
Could you give me a hand with this?
As always, after days of trying I've got answer 10 minutes after asking question. Here's what I came up with:
router.put("/profile/:id", async (req, res) => {
await Kit.findOneAndUpdate(
{ _id: req.params.id, profiles: { $elemMatch: { id: req.body.id } } },
{
$set: {
"profiles.$.name": req.body.name,
"profiles.$.profilePicture": req.body.profilePicture,
},
},
{ new: true, safe: true, upsert: true },
(error, data) => {
if (error) {
console.log(error);
} else {
console.log(data);
}
}
);
try {
res.status(202).json({ message: "Changed" });
} catch (err) {
res.status(400).json({ message: err });
}
});

findByIdAndUpdate do not update document

I am trying to update a field to the document with findByIdAndUpdate. The field I am trying to update is defined in the Bar Model. And I can also assure that req.body.bookId has a valid id.
Here's how my request looks,
app.patch("/foo", async (req, res) => {
try {
await validateId(req.body.bookId);
let doc = await Bar.findByIdAndUpdate(
req.body.bookId,
{ DateT: Date.now() },
{ new: true }
);
res.send(doc);
} catch (err) {
console.log(err);
}
});
Bar schema,
const mongoose = require("mongoose");
const barSchema = mongoose.Schema({
bookId: {
type: String,
unique: true,
},
DateT: {
type: Date,
default: null,
},
});
module.exports = mongoose.model("Bar", barSchema);
use updateOne, when you use async don't use .then() use try/catch
test it:
app.patch("/foo", async (req, res) => {
try {
let doc = await Bar.updateOne(
{ bookId : req.body.bookId },
{ DateT: Date.now() },
{ new: true }
);
res.send(doc);
} catch (error) {
console.log(error);
}
});
app.patch("/foo", async (req, res) => {
await Bar.findByIdAndUpdate(
req.body.bookId,
{ DateT: Date.now()},
(err, docs) => {
if (err) {
console.log(err);
} else {
res.send(docs);
}
}
);
});

ERROR in Read query using n AWS AppSync Chat Starter App written in Angular "Can't find field allMessageConnection"

const message: Message = {
conversationId: conversationId,
content: this.message,
createdAt: id,
sender: this.senderId,
isSent: false,
id: id,
};
this.appsync.hc().then((client) => {
client
.mutate({
mutation: createMessage,
variables: message,
optimisticResponse: () => ({
createMessage: {
...message,
__typename: "Message",
},
}),
update: (proxy, { data: { createMessage: _message } }) => {
const options = {
query: getConversationMessages,
variables: {
conversationId: conversationId,
first: constants.messageFirst,
},
};
// error on below line
const data = proxy.readQuery(options);
const _tmp = unshiftMessage(data, _message);
proxy.writeQuery({ ...options, data: _tmp });
},
})
.then(({ data }) => {
console.log("mutation complete", data);
console.log("mutation complete", data);
})
.catch((err) => console.log("Error creating message", err));
});
Analytics.record("Chat MSG Sent");
}
ERROR
errorHandling.js:7 Error: Can't find field allMessageConnection({"conversationId":"XXXXXXXXXXXXXXXXXXXXXXXXXXX","first":100}) on object {
"me": {
"type": "id",
"generated": false,
"id": "User:XXXXXXXXXXXXXXXXXXX",
"typename": "User"
}
}.

MongoDB query won't return object in my Express API (React)

I have done this so many times before, but I can't seem to find the issue, it's probably something small and stupid. Take a look at the /server.js file here! (Shortened for demonstration purposes)
/* Make Mongoose promise based */
mongoose.Promise = Promise;
mongoose.connect('mongodb://localhost:27017', options);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
/* Routes */
app.route('/games')
.post(postGame)
.get(getGames);
app.route('/games/:id')
.get(getGame)
.delete(deleteGame);
app.route("*").get((req, res) => {
res.sendFile('client/dist/index.html', { root: __dirname });
});
const port = 8080;
app.listen(port, () => {
console.log(`Connected! Server listening on port: ${port}`);
});
Then for my Game model, I have that in app/models/game.js.
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const gameSchema = new Schema(
{
name: {
type: String,
required:true
},
year: {
type: Number,
required:true
},
description: {
type: String,
required:true
},
picture: {
type: String,
required:true
},
postDate : { type: Date, default: Date.now }
}
);
export default mongoose.model('Game', gameSchema);
This is where I believe I am having the issue.
/* Import Game model schema */
import Game from '../models/game';
const getGames = (req, res) => {
Game.find({}, (err, games) => {
console.log(err, games)
if (err) {
res.send(err);
}
res.json(games);
});
}
const getGame = (req, res) => {
const { id } = req.params;
Game.findById(id, (err, game) => {
if (err) {
res.send(err);
}
res.json(game);
});
}
const postGame = (req, res) => {
let game = Object.assign(new Game(), req.body);
game.save(err => {
if (err) {
res.send(err);
}
res.json({ message: 'Game successfully created!' });
});
};
const deleteGame = (req, res) => {
Game.remove(
{ _id: req.params.id },
err => {
if (err) {
res.send(err);
}
res.json({ message: 'Game successfully deleted!' });
}
);
};
export {
getGames,
getGame,
postGame,
deleteGame
};
Just do be clear... I went into the mongo shell.
I did...
connecting to: test
> db.createCollection('Game')
> db.Game.insert({name: "SSB", year: 2001, description: "Fun Game", picture: "http://google.com", postDate: "2017-01-03T08:51:45.888Z"});
And when I type > db.Game.find({}); I am returned with exactly what I have...
{
"_id" : ObjectId("58c2223e32daa04353e35bdc"),
"name" : "SSB",
"year" : 2001,
"description" : "Fun Game",
"picture" : "http://google.com",
"postDate" : "2017-01-03T08:51:45.888Z"
}
You see when I go to http://localhost:8080/games I am returned with an empty JSON and I just wanna know why. I am 70% sure, it is because it isn't connected to the right collection but I don't remember how to test that :(
I wanted to make this a comment but it won't let me because I don't have a 50 reputation, but I believe I found the issue.
const getGame = (req, res) => {
const { id } = req.params;
Game.findById(id, (err, game) => {
if (err) {
res.send(err);
}
res.json(game);
});
}
In this piece of code you are setting the id to req.params, but you need to set it to req.params.id which is what you passed in your route.
Should look like this:
const {id} = req.params.id;
If you logged id, you would probably get an object that says:
{ id: "[whatever_id_you_put_here]" }
however if you log req.params.id you should get the correct id you put in that spot..
The reason you're getting [] is because you're actually connected to the database and you are actually trying to "get" something, but that something doesn't exist so it sends an empty response.
I hope this helps..