AndrewLeonardi
AndrewLeonardi

Reputation: 3512

Search for user with Mongoose

User's have accounts and can comment using a Comment Mongoose model. Is it possible to allow a user to enter a username in an text input and generate all user associated comments?

I've been trying to use db.users.find({"name") but I'm not sure how to pass a username from an input field to search. Any suggestions?

Thanks! The comment model is below. It connects each comment with a user.

var commentSchema = new mongoose.Schema({
    body: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String

    }
})

Upvotes: 2

Views: 2198

Answers (2)

Kuo-lun
Kuo-lun

Reputation: 65

Front-end

send your GET request with Query String to the Back-end API

<form method="get" action="/comments/user" >
   <input type="text" name="username" placeholder="username">
   <button type="submit">Search</button>
</form>

Back-end

write a API to deal with GET request and Mongoose Query

var app = express();

var Comment = mongoose.model('Comment', commentSchema);


app.get('/comments/user', function (req, res) {

    var query=Comment.find();

    //get the Query String here
    var filter=req.params.username;

    if(filter.length>0){

      query.where({author.username:filter});

    }

    query.exec(function (error, comment) {
           //send the result back to front-end
            res.json({ Comment: comment });
    });
});

Upvotes: 0

Shrabanee
Shrabanee

Reputation: 2766

You have to take the user name entered by another user from the text box and send it with the request to back end, something like {uName : 'user2'}.

Use the value from the object coming with the request and do find in your data base.

Something like below will be the backend code:-

var uName = req.params.uName

var cursor = db.users.find({username : uName.toString()}); 

Now cursor will give you record from user2 from your data base.

Upvotes: 2

Related Questions