Reputation: 55
I have a store object i retrieved from mongodb, I am interested in using the value store.comments.
i logged the store value and it is:
store:{ _id: 57e246f73e63d635cce3d174,
__v: 0,
comments: 57e246f73e63d635cce3d177,
loc: [ 105.832321, 105.233272 ],
name: '24 store',
reportedFalse: [],
products: [],
currentRanking:
{ likes: 57e246f73e63d635cce3d175,
dislikes: 57e246f73e63d635cce3d176 },
timePosted: Wed Sep 21 2016 11:38:15 GMT+0300 (Jerusalem Summer Time) },
then i logged the value of the object comments value - result.comments:
store comments objectid: undefined
and it seems when i try to search later by the comments value that it doesn't succeed in searching with it. because the search returns null, although i see that in my db i have a corresponding object in "comments" table/schema with the same id....
Comments.findById(commentsId,function(commentsErr,commentsArrObj){
...
cb(null, commentsArrObj._id);
}
i get:
TypeError: Cannot read property '_id' of null
heres part of my schema for reference:
name: String,
comments: mongoose.Schema.Types.ObjectId, // each comment has a object id - responder, link curl? crud? to his profile, profile pic, date time.
timePosted : { type: Date, default: Date.now },
currentRanking: {
likes: mongoose.Schema.Types.ObjectId, // a votes document
dislikes: mongoose.Schema.Types.ObjectId // a votes document
},
Upvotes: 0
Views: 708
Reputation: 2922
Console the error object "commentsErr" and then check what it is printing. If your commentsId type is changed to string then it may be the possible reason for not to finding the comments from schema. Try to convert it to ObjectId.
use:
Comments.findById(new mongoose.Types.ObjectId(id),function(commentsErr,commentsArrObj){
cb(null, commentsArrObj._id);
})
Suggestion: Use mongoose to populate records using ref so that you need not to find separate query to get comments.
Upvotes: 0
Reputation: 2983
In your schema you have to use 'ref'
comments: mongoose.Schema.Types.ObjectId,ref:'comments'(modal name of comments)
to refer comments schema and use populate the comments to get comments data.
Upvotes: 1