In my blog model;
...
user: {
type: mongoose.Types.ObjectId,
ref: 'users',
required: true,
},
...
And this is my user model;
follower: [
{
type: mongoose.Types.ObjectId,
ref: 'users'
}
],
So I'm gettting data like this;
const Post = await Blog.findOne({slug: post}).populate({
path: 'user',
select: 'name image count(follower)'
})
Of course count(follower) not working. I want to get followers count, how can I do that?
Related
I have an Order model:
const orderSchema = new mongoose.Schema({
order_items: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'OrderItem',
required: true
}],
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
shipping_address: {
type: String,
required: true
},
total_price: {
type: Number
}
});
And OrderItem model:
const orderItemSchema = new mongoose.Schema({
product_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
required: true
},
quantity: {
type: Number,
required: true
},
unit_price: {
type: Number,
required: true
}
});
And Product model:
const productSchema = new mongoose.Schema({
name: {
type: Map,
of: String,
required: true
},
unit_price: {
type: Number,
required: true
}
});
I tried to do double populate on find Order in the request like this:
const findOrder = await Order.find({ user: user_id }).populate('order_items').populate({ path: 'order_items.product_id', select: 'name' });
But I get only the first populate. When I tried the following:
const findOrder = await Order.find({ user: user_id }).populate('order_items').populate({ path: 'product_id', select: 'name' });
I got this error:
Cannot populate path product_id because it is not in your schema.
Set the strictPopulate option to false to override.
How can I get the product's name in a nested populate request?
Thanks...
Try with:
const findOrder = await Order.find({ user: user_id })
.populate({
path: 'order_items',
populate: {
path: 'product_id',
select: 'name'
}
}).exec();
For more information about the population across multiple levels read here.
I have the following Schema, and Base is the one-for-all collector of info:
const BaseSchema = mongoose.Schema({
creatorId: { type: mongoose.Schema.Types.ObjectId, required: true },
title: { type: String, required: true },
created: { type: Date, default: Date.now() },
users: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
messages: [{ type: mongoose.Schema.Types.ObjectId, ref: "Message" }]
});
And:
const BaseUserSchema = mongoose.Schema({
userId: { type: String },
baseId: { type: mongoose.Schema.Types.ObjectId },
created: { type: Date, default: Date.now() },
acceptedMembership: { type: Boolean, default: false },
isCreator: { type: Boolean, default: false }
});
(I have one for Message which looks about the same)
The latter one is referred to as User in const User = mongoose.model("User", UserSchema);
When I create a new Base I automatically add a user to a list within. In the DB i can see that the user does exist, but when I call the following the field does not populate:
Base.find({ creatorId: req.params.id })
.populate("users", "messages")
.exec()
.then(data => console.log(data));
I get the following from the console.log:
[ { created: 2018-09-05T03:41:45.416Z,
users: [],
messages: [],
_id: 5b8f508b2760c5329c13a9be,
creatorId: 5b86f7970cd98b2004969bf0,
title: 'testBase1',
__v: 1 } ]
When I first create the base via React front-end, and the base gets added to a list, I see that the users.length is 1, or the length of the automatically created user. When I refresh the page, however, the userlist is empty in the console.
Adding:
Forget to show how I populate the userlist upon creation:
router.post("/add", jwtAuth, (req, res) => {
Base.create({
creatorId: req.body.userId,
title: req.body.title
}).then(baseInfo => {
BaseUser.create({
userId: req.body.username,
baseId: baseInfo._id,
created: Date.now(),
acceptedMembership: true,
isCreator: true
})
.then(baseuser => {
baseInfo.users.push(baseuser);
return baseInfo.save();
})
.then(base => res.json(base.serialize()));
});
});
Answer:
.populate("users", "messages")
to begin with will return messages from users. It has to be two separate entries, like so:
.populate("users")
.populate("messages")
Then, in the model
users: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
refers to the wrong ref. It has to be
users: [{ type: mongoose.Schema.Types.ObjectId, ref: "BaseUser" }],
from
const BaseUser = mongoose.model("BaseUser", BaseUserSchema);
At last, I am not sure if this is needed, but I added a ref to each of the to-be-populated items:
baseId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "Base" },
baseId: { type: mongoose.Schema.Types.ObjectId, ref: "Base" },
Now it works like a charm, all without additional fetch
I Have following model for a team
var team = new mongoose.Schema({
supervisor: { type: mongoose.Schema.Types.ObjectId, ref: 'employee' }, // SupervisorId
commanders: [{
employee: { type: mongoose.Schema.Types.ObjectId, ref: 'employee' }, //under supervisor
level: { type: Number, defult: 1 }
}]
});
while fetching data from DB I am able to populate supervisor but not employees in commanders array
I tried something like below
db.team.findOne({
supervisor: employeeId
}).populate({
path: 'supervisor',
populate: {
path: 'commanders',
populate: {
path: 'employee',
model
}
}
})
Need help.!!
Try with This:
db.team.findOne({
supervisor: employeeId
}).populate('supervisor commanders.employee')
I'm trying to populate my Thread schemas GET response with all the comments related that that specific thread. I've specified a path within the Thread model to accept an array of Comments that I'll then populate when I request a thread, but it's continuing to be empty.
I'm not sure if I then need to push all the comments into the thread, but I think with the way I'm doing it, it's not required? I'm using Mongoose 4.4.19. I've followed along with the docs but still can't figure out where I've gone wrong.
Thread Schema:
const threadSchema = new Schema({
user: {
type: Schema.ObjectId,
ref: 'User',
required: true
},
title: {
type: String
},
content: {
type: String
},
category: {
type: String
},
comments: [{
type: Schema.ObjectId,
ref: 'Comment'
}]
}, {
timestamps: true
})
Comment Schema:
const commentSchema = new Schema({
user: {
type: Schema.ObjectId,
ref: 'User',
required: true
},
thread: {
type: Schema.ObjectId,
ref: 'Thread',
required: true
},
content: {
type: String
}
}, {
timestamps: true
})
Handles get requests:
export const index = ({ querymen: { query, select, cursor } }, res, next) =>
Thread.find(query, select, cursor)
.populate('user comments')
.then(threads => threads.map(thread => thread.view()))
.then(success(res))
.catch(next)
So I have a Mongoose query question that I can't seem to figure out. I'm trying to query a schema to find all documents in the collection that have a parameter specified user id in one of a few places... What I have so far is this:
Schema:
var Module = new Schema({
template: { type: Schema.ObjectId, ref: 'template' },
owner: { type: String, required: true, index: { unique: false } },
primary: { type: Schema.ObjectId, ref: 'User' },
users: [{ type: Schema.ObjectId, ref: 'User' }],
data: [],
children: [{ type: Schema.ObjectId, ref: 'Module' }],
parent: { type: Schema.ObjectId, ref: 'Module' }
});
Query:
Module.find()
.or([{owner: req.user.id}, {primary: req.user.id}])
.populate('primary users children parent template')
.exec(function (err, modules) {
...
}
So as of now, it seems to correctly find documents that have the req.user.id as the primary or owner field, but how would I also return all documents where the users array is also searched for this value?
Thanks!