Posts

Showing posts with the label mongoose-populate

Populate document with other fields

Image
Clash Royale CLAN TAG #URR8PPP Populate document with other fields I got the following document: { "_id": "5b5df332879b4769739e3ed0", "name": "Back workout", "exercises": [{ "_id": "5b5df9a7879b4769739e3ed1", "results": [{"reps":"10","weight":"85"}, {"reps":"8","weight":"70"}] }] } I want to populate the exercise based on the _id and also append the results data. _id results Expected output: { "_id": "5b5df332879b4769739e3ed0", "name": "Back workout", "exercises": [{ "_id": "5b5df9a7879b4769739e3ed1", "name": "EXERCISE_NAME", "results": [{"reps":"10","weight":"85"}, {"reps":"8","weight":"70"}] }] } My Schema looks ...

Populate from One Model to Another Using Mongoose/MongoDB in Node/Express Application

Image
Clash Royale CLAN TAG #URR8PPP Populate from One Model to Another Using Mongoose/MongoDB in Node/Express Application I am struggling to understand the populate method in Mongoose , while having trouble populating fields from one Mongoose model to another. The first model Schema is: var MprnSchema = new mongoose.Schema({ mprNo: {type: Number, unique: true, required: true}, siteName: String, buildingNo: Number, streetAddress: String, secondAddress: String, townCity: String, postCode: String, supplier: String, siteContactName: String, siteContactNo: String, }); module.exports = mongoose.model("Mprn", MprnSchema); And another Schema is: var FaultSchema = new mongoose.Schema({ jobRef: Number, mprNo: Number, requestedDate: {type: Date, default: Date.now}, attendedDate: {type: Date, default: null}, siteDetails: {type: mongoose.Schema.Types.ObjectId, ref: 'Mprn'}, faultIssue: String, }); However, when I try to p...

simplifying deep nested mongo query without using aggregate

Image
Clash Royale CLAN TAG #URR8PPP simplifying deep nested mongo query without using aggregate I'm trying to create a sort of newsfeed feature for my app. I'm trying to understand how to do it with a nested query in Mongo/Mongoose rather than using aggregate. (the rest of the app uses nested queries) and I'd prefer to not have to modify the query with vanilla javascript to get the perfect object if I don't need to. I'd like to get the friends of the current user, for each friend, get all of their posts and then sort it all by date. I want to make my current query more efficient as there's an extra step my query in Mongoose User.findOne({ _id: req.userId }, 'friends.user -_id') .populate({ path: 'friends.user', model: 'User', select: 'posts -_id', populate: { path: 'posts', model: 'Post', select: 'date author user desc -_id', ...