var mongoose = require('mongoose');
var FriendSchema = new mongoose.Schema({
requester: {
type: String,
required: true,
},
recipient: {
type: String,
required: true,
},
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var Friend = mongoose.model('Friend', FriendSchema);
module.exports = Friend;
I am trying to query it by using
Friend.find({"requester": { $in: [some id value]}}, function(err, fee){
console.log(fee.recipient);
});
and having it return the recipient id value..
Any suggestions would really be helpful, thank you.
you can use projection of mongo.db
the structure is like below ,
find(condition , requirefield , callback);
below is the example in which the fee will contain only the recipient
Friend.find({"requester": { $in: [some id value]}}, { _id : 0 , requester : 0 } ,function(err, fee){
console.log(fee.recipient);
});
you can refer https://docs.mongodb.com/manual/reference/method/db.collection.find/#projections for more reference.
I have a student collection when I want to report on a particular student with
studentId the report must be stored in report collection along with studentId
and what report I gave.I want to use individual collections
here is student schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var studentSchema = new Schema({
name: {
type: String,
required: true
},
dateofbirth: {
type: Date,
required: true
},
schoolname:
{
type:String,
required:true
},
standard:
{
type: Number,
required:true
}
}, {
timestamps: true
});
and here is report schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var reportSchema = new Schema({
date: {
type:Date,
required:true
},
comment:
{
type:String,
required:true
}
},
{
timestamps: true
});
var Report = mongoose.model('report', reportSchema);
module.exports = Report;
So how can I retrive studenId from student collection ?And how can I give report to a particular student?
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var studentSchema = new Schema({
name: {type: String, required: true},
dateofbirth: {type: Date, required: true},
schoolname: {type:String, required:true},
standard: {type: Number, required:true},
timestamps: true
});
var reportSchema = new Schema({
date: {type:Date,required:true},
comment: {type:String,required:true}
timestamps: true,
student_id: [{type: String, ref:'student',required: true}] //store your student{_id} relation here ref ==> is just a Collection name
});
mongoose.connect('mongodb://localhost/your_db_name_here', {
// using mongoose client to avoid promises exception
useMongoClient: true,
});
//just making your collection available to next controller.js file
module.exports= {
student : mongoose.model('student',studentSchema ),
report: mongoose.model('report', reportSchema)
};
controller.js I have been using express.js for your case
var db = require("./db.js");
var app = require("express")();
app.post("/api/student/register", (req, res) => {
var dbdata = {
name: req.body.name,
.......
}
db.student.create(dbdata, (er, callback) => {
if(er)return res.json("error");
return res.json("successfully inserted");
});
});
app.post("/api/student/report/create", (req, res) => {
//while creating a report you have to pass a Student primary key
var dbdata = {
date: req.body.data;
comment: req.body.comment,
student_id: req.body.student_id
// similar to foreign key relation ship}
}
db.report.create(dbdata, function(er, callback){
if(er)return res.json("err");
return res.json("successfully inserted");
});
});
your answer here
app.post("/particular/student/report", function(req, res){
db.report.find({student_id:"your student id here"}).populate('student_id').exec(function(err, data){
if(err)return res.json("db exception");
return res.json(data); //you will get all your student report for the particular student
});
});
here is
mongoose populate official docs
still if you have some other basic thing about mongoose or mean stack means kinldy refer to https://github.com/Muthukumars1994/Meanapp
I succeed to make a deep population with find and the search key in first model, but now i want to find by key on the sub object generated by the deep populate.
I have three models : Product, Category, and Event
I want to find my Products by e_fk_club_id that is in Event model
I tried two solutions but they didn't work
First solution in find :
model.find({'categories.events.e_fk_club_id':id})`
Second solution with match :
`$match : { e_fk_club_id : id }`
these are my models
product.js
var ProductSchema = new mongoose.Schema({
p_id: Number,
p_name: String,
p_fk_category: {type: mongoose.Schema.Types.ObjectId, ref: 'categories'},
}
, {collection: 'products'});
module.exports = mongoose.model('products', ProductSchema);
Category.js
var CategorySchema = new mongoose.Schema({
c_id: Number,
c_name: String,
c_fk_event: {type: mongoose.Schema.Types.ObjectId, ref: 'events'},
}
, {collection: 'categories'});
module.exports = mongoose.model('categories', CategorySchema);
Event.js
var EventSchema = new mongoose.Schema({
e_id: Number,
e_name: String,
e_fk_club_id: Number,
}
, {collection: 'events'});
module.exports = mongoose.model('events', EventSchema);
This is the code which i am trying to fetch the data :
getProductsByClub:function (id, callback){
var model = require("Product");
//model
model .find({'categories.events.e_fk_club_id':id})
.populate({
path:'p_fk_category',
model:'categories',
populate:
{
path:'e_fk_event',
model:'events',
//$match : { e_fk_club_id : id }
}
})
.exec (function(err, doc){
if (err) {
callback(err) ;
} else {
callback(doc) ;
}
})
},
Is There any solution.
Thank you in advance.
First Schema:
const ProviderSchema = new mongoose.Schema({
provName : { type: String, index: true }
});
module.exports = mongoose.model('provider', ProviderSchema);
Second Schema:
const WebProviderSchema = new mongoose.Schema({
userId : { type: Schema.Types.ObjectId, ref: 'users'},
providerId : { type: Schema.Types.ObjectId, ref: 'providers'}
});
module.exports = mongoose.model('webProvider', WebProviderSchema);
How do I join these two schemas?
So far if I do the following, I only get data from the second schema:
webProvider
.find({userId : '23423df234434bc956'})
.populate("providers")
.exec( function (error, listData) {
console.log(listData);
});
To populate you should use local field providerId. Should be .populate("providerId") instead of .populate("providers").
webProvider.find({userId : '23423df234434bc956'})
.populate("providerId")
.exec( function (error, listData) {
console.log(listData);
});
To populate multiple field can use like :
.populate("providerId userId")
or
.populate("providerId")
.populate("userId")
I want to get query of the mongoose in nodejs application as describe below out put.
user.js, comment.js and post.js are the model files I used.
user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var userSchema = new Schema({
nick_name:{type:String},
email: {
type: String,
trim: true,
required: '{PATH} is required!',
index: true,
},
},{ collection: 'user'});
var User = mongoose.model('User', userSchema);
module.exports = User;
comment.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var commentSchema = new Schema({
comment: type:String,
user_id:{
type:Schema.Types.ObjectId, ref:'User'
},
is_active :1
},{ collection: 'comment'});
post.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var postSchema = new Schema({
post: type:String,
user_id:{
type:Schema.Types.ObjectId, ref:'User'
},
is_active :1
},{ collection: 'post'});
wants to get out put as follows:
{
"nick_name":"prakash",
"email":"prakash#mailinator.com",
"comments":[
{
"comment":"this is a comment text1",
"is_active":1,
},
{
"comment":"this is a comment text2",
"is_active":1,
}
],
"posts":[
{
"post":"this is a post text1",
"is_active":1,
},
{
"post":"this is a post text2",
"is_active":1,
},
{
"post":"this is a post text3",
"is_active":1,
},
]
}
dependencies
"express" => "version": "4.7.4",
"mongoose" => "version": "4.4.5",
"mongodb" => "version": "2.4.9",
"OS" => "ubuntu 14.04 lts 32bit",
if query is not possible ,please suggests me a proper mongoose plugn.
but I don't want to any changes in user.js file and its userSchema object.
There are no 'joins' in Mongo. But what you would do is change your User Schema to store the ObjectId's of the Comment and Post documents in an array of your User. Then use 'populate' when you need the data with the user.
const userSchema = new Schema({
nick_name:{type:String},
email: {
type: String,
trim: true,
required: '{PATH} is required!',
index: true,
},
comments: [{ type: Schema.Types.ObjectId, ref:'Comment' }],
posts: [{ type: Schema.Types.ObjectId, ref:'Post' }]
}, {timestamps: true});
mongoose.model('User', userSchema);
Your query would then look something like this:
User.find()
.populate('comments posts') // multiple path names in one requires mongoose >= 3.6
.exec(function(err, usersDocuments) {
// handle err
// usersDocuments formatted as desired
});
Mongoose populate docs
It is possible .you should use aggregation.
it should work.
Initiate the variable
var mongoose = require('mongoose');
var userCollection = require('./user');//import user model file
var resources = {
nick_name: "$nick_name",
email: "$email"};
userCollection.aggregate([{
$group: resources
}, {
$lookup: {
from: "Comments", // collection to join
localField: "_id",//field from the input documents
foreignField: "user_id",//field from the documents of the "from" collection
as: "comments"// output array field
}
}, {
$lookup: {
from: "Post", // from collection name
localField: "_id",
foreignField: "user_id",
as: "posts"
}
}],function (error, data) {
return res.json(data);
//handle error case also
});
Of course it is possible, you just have to use populate, let me tell you how:
Import your schemas
var mongoose = require('mongoose');
var userSch = require('userSchema');
var postSch = require('postSchema');
var commSch = require('commentSchema');
Init all the necessary vars
var userModel = mongoose.model('User', userSch);
var postModel = mongoose.model('Post', postSch);
var commModel = mongoose.model('Comment', commSch);
And now, do the query
postModel.find({}).populate('User')
.exec(function (error, result) {
return callback(null, null);
});
commModel.find({}).populate('User')
.exec(function (error, result) {
return callback(null, null);
});
This way you get the user inside of your comment and your post, to get the post and comments inside of your user, you have to do 3 queries, one for the user, one for the comments and one for the post, and mix all together
you can consider using populate virtual with both comments and posts like docs (https://mongoosejs.com/docs/populate.html#populate-virtuals) in model User. And using like this:
User.find({filter}).populates('virtualComments').populate('virtualPosts')
Adding on to the answers above: What if we only want a few specific fields returned for the populated documents? This can be accomplished by passing the usual field name syntax as the second argument to the populate method:
Story.
findOne({ title: /casino royale/i }).
populate('author', 'name'). // only return the Persons name
exec(function (err, story) {
if (err) return handleError(err);
console.log('The author is %s', story.author.name);
// prints "The author is Ian Fleming"
console.log('The authors age is %s', story.author.age);
// prints "The authors age is null"
});
Reference: https://mongoosejs.com/docs/populate.html#field-selection
Use aggregate to do your work in a single query which is almost like a join.
var mongoose = require('mongoose');
var userModel = require('./user');//import user model file
let result = await userModel.aggregate([
{
$match: {
user: mongoose.Types.ObjectId(req.body.user_id),//pass the user id
}
},
{
$lookup: {
from: "comments",//your schema name from mongoDB
localField: "_id", //user_id from user(main) model
foreignField: "user_id",//user_id from user(sub) model
pipeline: [
{
$project:{ //use to select the fileds you want to select
comment:1, //:1 will select the field
is_active :1,
_id:0,//:0 will not select the field
}
}
],
as: "comments",//result var name
}
},
{
$lookup: {
from: "post",//your schema name from mongoDB
localField: "_id", //user_id from user(main) model
foreignField: "user_id",//user_id from user(sub) model
pipeline: [
{
$project:{//use to select the fileds you want to select
post:1,//:1 will select the field
is_active :1,
_id:0,//:0 will not select the field
}
}
],
as: "posts",//result var name
}
},
{
$project:{//use to select the fileds you want to select
nick_name:1,//:1 will select the field
email:1,
_id:0,//:0 will not select the field
comments:1,
posts:1
}
}
])