0

I am still trying to comprehend Mongoose/Mongo

Now in terminal When I do something like this in terminal

use library 
show collections 
db.authors.find().pretty()

I get something like this in logged

{
    "_id" : ObjectId("5bc8704f3a9828d5513505a2"),
    "name" : "Aman",
    "age" : "21",
    "__v" : 0
}
{
    "_id" : ObjectId("5bc870553a9828d5513505a3"),
    "name" : "Rohit",
    "age" : "20",
    "__v" : 0
}


{
        "_id" : ObjectId("5bc8704f3a9828d5513505a7"),
        "name" : "Aman",
        "age" : "21",
        "__v" : 0
    }
    {
        "_id" : ObjectId("5bc870553a9828d5513505a5"),
        "name" : "Rohit",
        "age" : "20",
        "__v" : 0
    }

Now, I want to have same data in my NodeJs i.e say, I want to find wherever the name is Rohit and want to link it with with some other db or schema.

how can I get the same output which I just obtained by running the above given command in terminal window of mongo in NodeJS

Obviously doing something like this console.log(db.authors.find()) won't work, so how can I get that?

1 Answer 1

2

This is how I usually write my database queries.

First create a schema that your model will follow. Don't worry this schema is flexible and you can change it at any time without affecting old data.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var authorSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  age: {
    type: Number,
    default: 20
  }
});

Next create a model from your schema.

var authorModel = mongoose.model('authorModel', authorSchema); 

Lastly query your model and get the value you need

authorModel.find(
        {
          name: 'Rohit'
        },
        function (err, result) {
          console.log(result)
         });

I put my schema and controller on separate files. How you organise your code structure is up to you.

I pretty much followed this blog when I first learnt to build APIs on NodeJS. You might find this useful as well!

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

Comments

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.