I have two collections User and Taxdetails , I want the name and phone number from User and payment details from Taxdetails joingin on user_id in both collections.
I am doing this:
User
.find()
.exec(function(err, userDetails) {
if (err) {
console.log("error in user collection");
res
.status(400)
.json({ 'message':'error','success':false });
} else {
var userid = userDetails.map(function(obj) {
return obj._id;
});
Taxdetail
.find()
.exec({ user_id : { $in : userid } },function(err, requests) {
if(err){
console.log("error in TaxDetails collection");
res
.status(400)
.json({ 'message':'error','success':false });
}else{
console.log("Success, got some data");
res
.status(200)
.json(requests);
}
});
}
});
You may want use referenced schema in your User schema and then populate it like this:
var taxDetailSchema = new Schema({
title: String
});
var taxDetail = mongoose.model('taxDetail', taxDetailSchema);
var userSchema = new Schema({
name: String,
taxDetails: [{ type: Schema.Types.ObjectId, ref: 'taxDetail' }]
});
Your query would look like this:
User
.find()
.populate('taxDetails')
.exec(function(err, users) {
});
The users
should look like this:
[
{
name: 'Some Name',
taxDetails: [
{ title: 'Some Title' },
{ title: 'Some other Title' }
]
}
]
Mongoose documentation here
Hope it helps
We will make Schema a user and another post as you see below
const { Schema, model} = require("mongoose");
const UserSchema = new Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true
},
posts:[{
type: Schema.Types.ObjectId, ref: "Post"
}]
});
const PostSchema = new Schema({
title: String,
desc: String,
User: {type: Schema.Tpes.ObjectId, ref: "User"}
});
export const Post = model("Post", PostSchema);
export const User = model("User", UserSchema);
Then
try {
const user = User.create({
name:"Robert Look",
email: "phpcodingstuff@gmail.com"
})
try {
const post1 = Post.create({
title: "This is a first post",
desc: "this a a first description"
user: User._id // assign the _id from the user
});
} catch (err) {
console.log(err.message)
}
} catch (err) {
console.log(err.message)
}
Reading Models
User.findOne({
name: "Robert Look"
}).populate('posts').exec((err, user) =>{
if(err){
console.log(err)
}else{
console.log(users.posts[0].desc)
}
});
Conclusion
We saw above how to use populate We also saw how joining two documents in mongoose (MongoDB), if you write the query correctly then you will get a good result or your JSON.
More Information: Mongoose
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.