在使用 mongoose 之前,我曾使用sequelize。决定尝试猫鼬并发现在我的代码中忽略了跳过和限制选项。
这是我的模型:
const User = new Schema({
login: { type: String, reqiried: true, unique: true },
email: { type: String, reqiried: true, unique: true },
password: { type: String, require: true },
avatar: { type: String },
posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
likedPosts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
repostedPosts: [
{
post: { type: Schema.Types.ObjectId, ref: "Post" },
text: { type: String },
},
],
});
服务代码:
export const getReposted = async (userId, limit, skip) => {
const reposted = await User.findOne({ _id: userId })
.populate({
path: `repostedPosts`,
skip: `${skip}`,
limit: `${limit}`,
populate: {
path: "post",
populate: {
path: "author",
select: "login",
},
},
})
.select("repostedPosts -_id");
return reposted;
};
但它返回了数组内的所有对象。
相同的代码适用于 LikePosts 和 posts。
如果你能帮忙,我会很高兴。
除了更改文档结构之外尝试了所有方法,这可能会起作用,但我想知道我是否遗漏了某些内容。
也许我错过了一些东西,但我相信
skip
和limit
是“查询选项”而不是“填充选项”,这将使它们成为options
中.populate
对象的属性。这个有用吗:
export const getReposted = async (userId, limit, skip) => {
const reposted = await User.findOne({ _id: userId })
.populate({
path: `repostedPosts`,
options: {
skip: `${skip}`,
limit: `${limit}`,
},
populate: {
path: "post",
populate: {
path: "author",
select: "login",
},
},
})
.select("repostedPosts -_id");
return reposted;
};