2

What i am trying to do is the write a javascript function to access a defined articles schema in my .js file.

I have already determined that the below queries work in the mongodb terminal:

    db.articles.ensureIndex( { "comments.user_id" : 1 } )
        db.articles.find( { "comments.user_id" : 987654 } ) // returns all document fields, meaning X and Y including comments

        db.articles.find( { "comments.user_id" : 987654 }, 
{ "title" : 1, "comments.user_id" : 1 })   //some trimming

The purpose of the javascript function is to retrieve all comments made by a specific user, is my below attempt correct corresponding to the above mongodb queries? Are the style, syntax considered good practice?

exports.allCommentsByUser = function(userId){ 
   db.articles.ensureIndex({"comments.user_id" : 1})
    var allComments = db.articles.find({"comments.user_id" : userId}, 
                  { "title" : 1, "comments.user_id" : 1 });
    return allComments;
}

Q: Further, how do i convert the above javascript function to a closure function?

Note: i am using mongoose as a wrapper

1 Answer 1

1

That won't work because allComments is a Mongoose Query object, not the results. You need to add a callback parameter to your allCommentsByUser method that the method will use to provide the results back to the caller once the async find call completes.

exports.allCommentsByUser = function(userId, callback){ 
    db.articles.find(
        {"comments.user_id" : userId}, 
        { "title" : 1, "comments.user_id" : 1 }, 
        callback);
};

Usage of the method:

x.allCommentsByUser(userId, function (err, articles) {
    if (err) {
        console.error(err);
    } else {
        console.log(articles);
    }
});

Not sure what you're asking in your second question regarding a 'closure function'.

Sign up to request clarification or add additional context in comments.

2 Comments

You wouldn't want to put the ensureIndex call in the allCommentsByUser method. You would do that as part of your schema definition.
can you show me an example of putting the ensureIndex as part of schema definition please?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.