Rahal Rahal - 14 days ago 9
Node.js Question

mongoose find by ObjectId

I'm defining a mongoose schema like this

var accountPostSchema = new mongoose.Schema({
account: {
id: { type: mongoose.Schema.Types.ObjectId, ref: 'Account' }
},
post: {
id: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' }
}
});

app.db.model('AccountPost', accountPostSchema);


When a user(account holder) create a post, I save the post in a Post schema and get the 'postId'. Then I save the 'postId' and the 'accountId'
in the above accountPostSchema like this

var fieldsToSet = {
post: {
id: postId
},
account: {
id: accountId
}
};

db.models.AccountPost.create(fieldsToSet, function(err, accountPost) {
if (err) {
// handle error
}

// handle success
});


After entering few postId's and accountId's, I see the following results in the mongo shell

> db.accountposts.find({})
{ "_id" : ObjectId("5835096d63efc04da96eb71e"), "post" : { "id" : ObjectId("5835096d63efc04da96eb71d") }, "account" : { "id" : ObjectId("5833c920c868d7264111da69") }, "__v" : 0 }
{ "_id" : ObjectId("583509e12052c7a2a93c4027"), "post" : { "id" : ObjectId("583509e12052c7a2a93c4026") }, "account" : { "id" : ObjectId("5833c920c868d7264111da69") }, "__v" : 0 }


Now how do I find all the matching 'Posts' given an accountId? (not the postId's)

For example if I the accountId is 583509e12052c7a2a93c4026, I need to find Posts with Post._id=5835096d63efc04da96eb71d and Post._id=583509e12052c7a2a93c4026

What is the query I should run to get the matching Posts?

Answer

I think, you should follow this way to get all the posts associated with particular accountid.

db.accountposts.find({'account.id' : accountId})
.populate('post.id')
.exec();