I have a model that may or may not be related to another model. here is my model structure:
// Post.js
attributes: {
sender: { model : 'user' },
}
// User.js
attributes: {
posts: { collection: 'post', via: 'sender', dominant: true }
}
So the post model my or may not be attached to a sender. sender can either be a user or null.
I need to be able to get all of the posts that are specific to a particular user and all posts that do not have a sender. Once I have both of these I need to concatenate them. Here is the code I have to do this:
// Before this I use a native query to get a list of posts with no sender. This is "searchIds".
filterData.id = searchIds;
filterData.subject = 1;
posts = [];
// Populate questions that were sent to all users
Post.find()
.where(filterData)
.exec(function (err, response) {
if(err) return res.serverError(err);
// We add all of the posts with no senders to the messages array
if (response.length > 0){
posts = posts.concat(response);
}
delete filterData.id;
// Now we get the posts specific to this user.
User.findOne({id:id})
.populate('posts',{ where: filterData })
.exec(function(err, results){
if(err) return res.serverError(err);
if (results && results.posts && results.posts.length > 0){
posts = posts.concat(results.posts);
}
return res.json(posts);
});
});
This works find and gets me an array of posts made by that specific user and all posts that do not have a sender, however what I need to do now is paginate this list. The way I would usually do it is to use the Sails/Waterline paginate method but because I am concatenating two separate DB calls together I dont know how I can do this?
You could just combine both queries with Waterlines or
feature.
Post.find({
or: {
{sender: null}, // finds 'no sender' posts
{sender: senderId} // finds posts where sender's id is senderId
}
})
.paginate({ page: 2, limit: 10 })
.then(function(posts) {
return res.json(posts);
})
.catch(function(err) {
return res.serverError(err);
})
I'm pretty sure you could even write the find query like
Post.find({sender: [null, senderId]})
and get the same result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.