buydadip
buydadip

Reputation: 9437

How to log mongoDB query to terminal using Node JS

I am using the following code to add a schema model to my database...

db.on('error', console.error);
db.once('open', function() {
        var Schema = new mongoose.Schema(
        name: String,
        _id: String
    });
    var User = mongoose.model('User', Schema);
    new User({

        name: "Help me!",
        _id: "12345"

    }).save(function(err, doc) {
    if (err)
        throw err;
    else 
        console.log('save user successfully...');
        console.log(User); //This is the problem
    });

The code works fine, the schema gets loaded into the database, but the problem is I want to print the schema I just added on to the console window.

In the code above, I tried using console.log(User), but when I do so, all I get is a bunch of jargon that I cannot understand.

If I query the data using mongo terminal...

db.users.find()

I get...

{ "_id" : "12345", "name" : "Help me!"}

This is what I want to print to my console window when I run the code above, how can I do this?

Upvotes: 2

Views: 1665

Answers (2)

noonkay
noonkay

Reputation: 123

You are console logging the User model and not the instance of the User which you created. Try console.log(doc); instead to see the new document you just created.

Upvotes: 1

chridam
chridam

Reputation: 103445

To get back the document you just added, try using the create() method:

var Schema = new mongoose.Schema(
        name: String,
        _id: String
    }),
    User = mongoose.model('User', Schema),
    obj = {
        name: "Help me!",
        _id: "12345"
    };
User.create(obj, function(err, user) {
    if (err)
        throw err;
    else 
        console.log('save user successfully...');
        console.log(user); //This is the solution
});

Upvotes: 1

Related Questions