2

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?

2 Answers 2

1

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

This helped me indirectly, Im my code all I had to do was console.log(doc)
1

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.

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.