Reputation:
I'm working on a node app (with IOS front end) right now and stumbled upon this issue. I used mongodb together with mongoose. I have this route, /get that receives the correct user id and tries to find all 'Voots' with that same user id. This is what a 'Voot' looks like:
{
"_id": "59db9fa2659bb30004899f05",
"title": "Pizza!",
"body": "hoppakeeee",
"user": {
"__v": 0,
"password": "$2a$10$Rwb5n7QoKaFaAOW37V0aWeEeYgfn6Uql474ynUXb83lHi7H2CuB1u",
"email": "[email protected]",
"name": "Noelle Schrikker",
"_id": "59db9ecf659bb30004899f04"
},
"__v": 0,
"downVotes": [],
"upVotes": []
},
As you can see, it has a property called user
which is a user object containing a name, email, password and _id
.
I do this with my request:
// Send all voots from the specific user
Voot.find({"user._id": userId}, function(err, voots) {
if (err) {
console.log(err);
res.status(400).send(err)
res.end()
}
if (voots) {
res.status(200).send(voots)
res.end()
}
})
I try to find all voots with their user
having the property of userId
(this is the correct user ID). However, this doesn't work. I tried finding it by "user.email"
which does work. I think it has something to do with the _
before id
. Any comment is appreciated!
Voot shema:
var vootSchema = new mongoose.Schema({
title: String,
body: String,
user: {
type: mongoose.Schema.Types,
ref: 'user'
},
upVotes: [String],
downVotes: [String]
})
var Voot = mongoose.model('voot', vootSchema)
Userschema:
var userSchema = new mongoose.Schema({
name: String,
email: String,
password: String
})
var User = mongoose.model('user', userSchema)
Upvotes: 1
Views: 5583
Reputation:
Got it! I added .ObjectId
in the Voot schema, now I can access the User object using population. I can now find the Voot by using:
Voot.find({“user”: userId}).populate(‘user’) .exec()
Thanks for all the answers!
Upvotes: 0
Reputation: 12071
Use just user in your query rather than user._id:
Voot.find({ "user": userId }, function(err, voots) {
// Callback code
})
The id or the referenced user is stored in the user field. The user sub-document, and therefore the user._id field, will only be available after population.
Upvotes: 0
Reputation: 5708
I would assume that _id
of user
object is not a string. That said you need to modify your query to use ObjectId
instead of string:
Voot.find({"user._id": ObjectId(userId)}, function(err, voots) {
if (err) {
console.log(err);
res.status(400).send(err)
res.end()
}
if (voots) {
res.status(200).send(voots)
res.end()
}
})
If you don't want to change your query, you could change your user
schema, so that _id
is string. Then your query should start working:
var userSchema = new mongoose.Schema({
_id: { type: String },
name: String,
email: String,
password: String
})
var User = mongoose.model('user', userSchema)
Upvotes: 1