How to achieve series of task using bluebird promise? - node.js

I've three models:
Users
Flats
Rooms
I want to get information(list) of those users who has no flat and has flat but has zero rooms (means room entry not found for particular flat).
User Model
username:{type: String},
password:{type: String},
...
Flat Model:
userid: { type: Schema.ObjectId, ref: 'User' },
flatname:{type: String}
...
Room Model:
roomid: { type: Schema.ObjectId, ref: 'Flat' },
roomnumber:{type: String}
...
I want to achieve this functionality using bluebird module promises.
I've already did :
var User = require('../models/User');
Promise.promisifyAll(User);
var Flat= require('../models/Flat');
Promise.promisifyAll(Flat);
var Room= require('../models/Room');
Promise.promisifyAll(Room);

Related

How to access and populate a referenced object schema in a larger document (MERN)

Making an app with a variety of schemas, many having other objects (Schema.Types.ObjectIds) as their properties.
When doing this, I can access the sub-object's property, as long as that sub-object's property is a string. But I'm having issues with it if that sub-object's property is yet another object (and then I need to query properties from that, string or not). For example, the first works fine:
user schema-> friends property of user (which is a list of user objects) -> username property of friend (which is a string)
But this I'm having issues with, I'm getting a string id and not the actual object**:
user schema-> profilePosts property of user (which is a list of profilePost objects) -> author property of profilePost (which is a user object)** -> author username property of profilePost (which is a string)
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: {type: String, required: true},
password: {type: String, required: true},
friends: [{type: Schema.Types.ObjectId, ref: "User"}],
profilePosts: [{type: Schema.Types.ObjectId, ref: "ProfilePost"}],
friendRequests: [{type: Schema.Types.ObjectId, ref: "User"}],
})
module.exports = mongoose.model('User', UserSchema);
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ProfilePostSchema = new Schema({
date: {type: Date, required: true},
author: {type: Schema.Types.ObjectId, ref: "User"},
content: {type: String, required: true},
comments: [{type: Schema.Types.ObjectId, ref: "ProfilePostComment"}],
likes: [{type: Schema.Types.ObjectId, ref: "User"}],
hostProfile: {type: Schema.Types.ObjectId, required: true,ref: "User"},
})
module.exports = mongoose.model('ProfilePost', ProfilePostSchema);
exports.user_friends_render = async (req,res) => {
try {
const ViewedProfile = await User.find({}, 'username friends profilePosts friendRequests').populate('friends').populate('profilePosts').populate('friendRequests');
res.status(200).json(ViewedProfile);
} catch(error) {
res.status(200).json({message: error.message});
}
}
objects are string ids instead of objects
Mongoonse populate root object but not implicit deep populate
You can replace string by object as argument at populate method,
for provide full path to populate
const ViewedProfile = await User
.find({}, 'username friends profilePosts friendRequests')
.populate('friends')
.populate({
path: "profilePosts",
populate: [
{
path: "author",
// model: UserModel
},
{
path: "comments",
// model: ProfilePostCommentModel
},
{
path: "likes",
// model: UserModel
},
{
path: "hostProfile",
// model: UserModel
}
]
})
.populate('friendRequests');
You can see fully post at this problem.

Check against multiple fields when using Mongoose Virtual schema?

I am a little stuck with trying to figure out the best way to populate a virtual schema in my db. In this instance, I want to check against multiple fields but I do not know any way to do this or alternative ways.
I had hoped I could just use some string arrays in the 'localField' & 'foreignField' keys of the virtual schema but this was not the case.
The user has a 'Series' _id saved, and the virtual schema 'leagues' gets all leagues that the user is entered into too, the catch is a league belongs to different Series. I want to only retrieve the leagues that the user is entered into & that match up with the user's series _id also...
As you can see currently this virtual schema just returns all the leagues the user is entered into regardless of the series. :(
Any ideas? I have been very confused about how to achieve this.
const schema: mongoose.Schema = new mongoose.Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
auto: true
},
username: {
type: String,
unique: true,
},
series: {
ref: 'Serie',
type: mongoose.Schema.Types.ObjectId,
autopopulate: {
maxDepth: 1,
select: ['title']
}
}
});
schema.virtual('leagues', {
ref: 'League',
localField: '_id',
foreignField: 'users',
autopopulate: {
maxDepth: 1,
select: ['title', 'engineSize', 'host', 'series']
}
});
The league schema looks like this
const schema: mongoose.Schema = new mongoose.Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
auto: true
},
title: String,
series: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Serie',
},
users: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
}]
});
This was my solution to checking against multiple fields in mongoose using a getter.
schema.virtual('motoduel').get(function () {
return motoduelModel.findOne({
event: this.series.upcomingEvent._id,
riderGroup: this.riderGroup._id
});
});

How to populate the model of populated model in mongoose

I come from the MySQL background. I am new to MongoDB. How can I get the details model of a populated model? Please help me
Listing Model
var listing = new mongoose.Schema({
ru_id : [{type: mongoose.Schema.Types.ObjectId, ref: 'Rentable_unit' }],
pro_id : [{type: mongoose.Schema.Types.ObjectId, ref: 'Property' }]
})
Property Model
var property = new mongoose.Schema({
address_id : [{type: mongoose.Schema.Types.ObjectId, ref: 'Address' }],
pro_authority : [{type : mongoose.Schema.Types.ObjectId, ref: 'User' }]
})
Address Model
var address = new mongoose.Schema({
address_line_1: { type: String },
address_line_2: { type: String }
})
I need to get the data from listing address based on property how can I do this.
You will have to load your listing, then your property and then the address with three queries. It's referenced in the article below as application-level join.
If you need to do this a lot you should consider changing your schema design. You could check this blog post from mongodb for possible solutions.

Mongoose query from two schemas that share same reference

Suppose I have two schemas:
1. UserEnrolledCourses
var userCoursesSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'users'},
courseId: { type: mongoose.Schema.Types.ObjectId, ref: 'courses'},
isEnrolled: Boolean,
});
2. CourseResources
var resourcesSchema = new mongoose.Schema({
courseId: { type: mongoose.Schema.Types.ObjectId, ref: 'courses', required: true },
type: {type:String, required:true},
});
Both of them shared the same courseId reference from courses schema.
So, my aim is to generate result from query that for each courseId that one user enrolled, list all of the resources that available. Is that possible?
In mongoDB, you are performing queries on one concrete collection. The only exception is the left outer join with new method $lookup in aggregation for mongodb 3.2 and more. Look at documentation

Complex sort with Mongoose

I'm new in Mongoose and I want to create a 'complex' sorting. So I have the following schemas:
var UserSchema = new Schema({
firstName: String,
lastName: String,
...
skills : [{ type: Schema.Types.ObjectId, ref: 'Skill' }]
});
var ProjectSchema = new Schema({
name: String,
description: String,
...
skills : [{ type: Schema.Types.ObjectId, ref: 'Skill' }]
});
var SkillSchema = new Schema({
name: String
});
So given those schemas what I need is to sort by the matching percentage between the user skills and the project skills, so basically I want to show first the projects that are more related to the user. Is that possible by using just mongoose? If so I guess I will need to create a sorting function that I can pass to the query or something.
Thank you!

Resources