How to log mongoDB query to terminal using Node JS - 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?

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
});

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.

Related

Update element in Array of Mongoose schema

I am trying to update one element of snippets in my mongoose schema.
My Mongoose schema.
const Schema = new mongoose.Schema({
// ...
createdAt: Date,
snippets: {} // here I push ['string..', ['array of strings..']]
})
Here's a view of snippets in Compass.
Problem with the code below is that it completely erases other elements stored, other than that it works. Unable to specify that I want to update snippets[0], not entire thing..?
User.findOneAndUpdate({ username: req.session.user.username },
{ $set: { snippets: [snippet] } }, callback)
Tried using findOne andsave but it wouldn't update the db.
const snippet = [req.body.code, [req.body.tags]]
User.findOne({ username: req.session.user.username }, function (err, fetchedUser) {
if (err) console.log(err)
fetchedUser.snippets[req.params.id] = snippet // should be set to new snippet?
fetchedUser.save(function (err, updatedUser) {
if (err) console.log(err)
console.log('edited')
// ...
})
})
Any suggestions?
I thought I tried this earlier, but apparantly not.
Using fetchedUser.markModified('snippets') solved my issue with findOne/save not actually saving to DB.

object referencing/mongoose-mongodb

I have been taking colt Steeles's web development bootcamp classes,so i am on the associations topic. tried writing code to do a one to many association via object referencing, the code appears thus
var mongoose= require("mongoose");
mongoose.connect("mongodb://localhost/blogApp_demo_2",{useNewUrlParser:true});
var postSchema= new mongoose.Schema({
title:String,
content:String
});
var post= mongoose.model("post",postSchema);
var userSchema = new mongoose.Schema({
name: String,
Email:String,
posts:[
{
type:mongoose.Schema.Types.ObjectId,
ref:"post"
}]
});
var user= mongoose.model("user",userSchema);
post.create(
{
title:"beauty in the lilies",
content: "there is so much to marvel in lilies"
}, function(err,post){
user.findOne({email:"deleomoarukhe#yahoo.com"}, function(err,foundUser){
if(err){
console.log(err);
} else{
foundUser.posts.push(post);
foundUser.save(function(err,data){
if(err){
console.log(err);
}else{
console.log(data);
}
});
}
});
});
but on trying to execute this code it gives me this error
TypeError: Cannot read property 'posts' of null
tried everything i can to get this code running, to no avail.
p.s the code was to add a further comment to an already existing user.

saving to mongodb with mongoose fails but no error shown

Am creating a nodejs bookstore app. Books details which are strings/numbers/booleans are to be saved in MongoDB using mongoose while the book cover image is to be saved in an uploads folder in my root directory using multer.Here is my mongoose schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//Creating schema and model
var BookDataSchema = new Schema({
title: String,
author: String,
isbn: String,
price: Number,
quantity: Number,
availability: Boolean,
description: String
});
var BookData = mongoose.model('BookData', BookDataSchema);
module.exports = BookData;
This is the code to perform the saving function:
router.post('/', function (req, res) {
var newBook = new BookData({
title: req.body.bkname,
author: req.body.bkauthor,
isbn: req.body.bkisbn,
price: req.body.bkprice,
quantity: req.body.bkquant,
description: req.body.bkdesc
});
newBook.save(function (err) {
if (err) {
console.log(err);
} else {
console.log(newBook);
console.log('Book Details saved successfully');
}
});
}, function(req, res) {upload(req, res, (err) => {
if (err) {
console.log(err);
res.render('admin', {
msg: err
});
} else {
console.log(req.file);
return res.render('admin');
}});}
);
The main problem is when I console.log(newBook) or console.log(result) or check in mongo shell all I see is { _id: 5b4fdba80420890764ce13bf, __v: 0 }, only the id that mongodb creates is displayed which means the other data is not saved and worse it does not proceed to the other callback function. Am not getting any error apart from this warning:
(node:1220) [DEP0079] DeprecationWarning: Custom inspection function on Objects via .inspect() is deprecated
I tested the code for saving the image excluding that for saving the other data and it worked fine. Kindly help on what could be the problem and also advise me on how I would ensure the admin page is rendered only after everything has been saved. See the whole project in_this_git_repo

How to update linked document in mongoose from parent?

I have a User model with a profile field pointing to profile model, like
UserSchema = new Schema({
name: {
type: String,
require: true,
unique: false,
},
profile:{type:Schema.Types.ObjectId, ref: 'Profile'}});
Now it is saving fine, but I want to update the User and Profile at the same time by sending an object like:
{
name : 'some name',
profile.location : 'some location'
}
my simple update code:
User.update({_id:userId},req.body,{},function(){
res.status(204).end();
});
It seems to only update the User's name, but not the linked Profile document's properties. What would be the best way to do this?
The Population (ref used in profile) is introduced into Mongoose,
Because there are no joins in MongoDB but sometimes we still want references to documents in other collections. Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s).
So it is not related to update operation for the reference document. Here are one sample codes to meet your requirement.
User.update({_id: userId},
{name: req.body.name}, function(err, u) {
if (err)
console.log(err);
else {
Profile.update({_id: u.profile},
{location: req.body.profile.locatio},
function(err) {
// error handling
})
}
});
If you are using DaftMonk's Angular Fullstack Generator, then just do this :
Install lodash npm install lodash
Include lodash in your JS file like this : var _ = require("lodash");
Finally do this :
var newUser = {};
newUser.name = "Some Name";
User.findById(userId, function(err, user){
if(err) console.log(err);
var updated = _.merge(user, newUser);
updated.save(function (err) {
if (err) console.log(err);
Profile.findById(user.profile._id, function(err, profile){
profile.location = "some location";
profile.save(function(err){
if(err) console.log(err);
console.log("Updated User and Profile");
});
});
});
});
Hope this helps.

How do you get a grunt task to save a new simple mongodb document?

I've got a problem with using mongoose and custom grunt tasks together. All i want to do is make a task that behaves like a simple put request, by taking the parameters I give the task in the command line and processing/saving them to the database. However, when I expect to find it in the DB after adding it.. I can't find it anywhere.
The goal is to create a new company and save 4 simple parameters save from a "grunt addcompany:a:b:c:d" command.
Here is the "company" model (I've kept it very basic):
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var Company = new Schema({
name: String,
email: String,
info: String,
also: String
});
module.exports = mongoose.model('Companies', Company);
This is at the top of my Gruntfile.js:
var schemaCompany = require('./models/company'),
mongoose = require('mongoose'),
db = mongoose.connection,
Company = mongoose.model('Companies', schemaCompany);
This is the task:
grunt.registerTask('addcompany', 'add a company', function(n,e,i,a) {
var done = this.async();
mongoose.connect('mongodb://localhost/app-test');
db.on('open', function () {
var co = new Company({
name: n,
email: e,
info: i,
also: a
});
co.save(function (err) {
if (err) return handleError(err);
console.log('success!');
});
console.log(co);
db.close();
});
});
When I type this in the CLI:
grunt addcompany:name:email:description:more_stuff
The CLI returns with:
Running "addcompany:name:email:description:more_stuff" (addcompany) task
{
"name": "name",
"email": "email",
"info": "description",
"also": "more_stuff",
"_id" : ObjectID(" ~object id here~ "),
"__v" : 0
}
Although it creates an Object ID, it never saves anywhere. Nothing is showing up in the companies collection in the app-test db. What am I missing?
Thank you for your help!
Try this:
db.on('open', function () {
var co = new Company({
name: n,
email: e,
info: i,
also: a
});
co.save(function (err) {
// log the doc
console.log(co);
// log the error
console.log(err);
if (err) return handleError(err);
console.log('success!');
// close the database after 'co' is saved.
db.close();
done(true);
});
});

Resources