skip to Main Content

I have been trying to get the specific value from database of MongoDB in node.js using. I have used find() and findOne() but in both case I am getting some object like thing in console.
This is my code:

const mongos=require('mongoose')
const { default: mongoose } = require('mongoose')
mongos.connect("mongodb://localhost:27017/chat")
const upSchema=mongos.Schema({
    user:String,
    password:Number,
    email:String
})
const chat_up =mongos.model('up',upSchema)

let userName=req.body.user
    let pass=req.body.pass
    let name=chat_up.findOne({"user":userName,"password":pass})
    console.log(name)

This is my database:

{ "_id" : ObjectId("624057512a4c11d61e4a8226"), "user" : "Ashutosh", "password" : 12345, "email" : "[email protected]", "__v" : 0 }
{ "_id" : ObjectId("62407c03f1c4d198344907a7"), "user" : "wertgsdfbsrthfx", "password" : 1234345, "email" : "[email protected]", "__v" : 0 }
{ "_id" : ObjectId("62407c1ff1c4d198344907a9"), "user" : "", "password" : null, "email" : "", "__v" : 0 }

How can I get only value of "user" like "Ashutosh" using query in my console.

2

Answers


  1. You need to project the field:

    db.collection.find({
     "user": "Ashutosh"
    },
    {
     user: 1,
     _id: 0
    })
    

    playground

    Login or Signup to reply.
  2. in order to print the username you just need:

    console.log(name.user)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search