I'm wondering if anyone can help me with the following problem. I currently have a collection of posts. On each post when a user marks it as read it pushes their user _id onto an array inside the the post document.
I'm then trying to read all the posts, and find which users have not read the document. My idea was to try us this $nin function whilst cycling through the posts and then storing them in a new object that I can call with the same index number. However I'm struggling to find the correct syntax to get the it due to object been in string format.
const allPosts = await Post.find({});
for (let i = 0; i < allPosts.length; i ) {
console.log(i)
const findUsers = await User.find({ _id: { $nin: ObjectID([allPosts[i].posthideuser]) } })
console.log(findUsers);
}
Any help appreciated I've been on this a while now.
CodePudding user response:
You are converting the whole array into an ObjectID
instead you want to convert individual values. Use .map()
with ObjectId
constructor
const allPosts = await Post.find({});
for (let i = 0; i < allPosts.length; i ) {
console.log(i)
const objIds = allPosts[i].posthideuser.map((x) => new mongoose.Types.ObjectId(x));
const findUsers = await User.find({ _id: { $nin: objIds } })
console.log(findUsers);
}