mongoose js won't print out query value - javascript

I want to create using mongoose js a collection of kitten with this document in it {name: "mike"}.
After creating this document I want to print it's value.
I wrote this code below.
2 problems:
this code doesn't end (meaning when I wrote node file.js the cmd line stays open (stucked) and no return value is return (infinite loop like in a server).
the code doesn't print the value of "mike". just create this doucument...
what am I doing wrong?
thanks
var mongoose = require('mongoose');
var url = 'mongodb://Yotam:Yotam#ds023475.mlab.com:23475/small-talkz';
mongoose.connect(url);
var kittySchema = mongoose.Schema({
name: String
});
var Kitten = mongoose.model('kitten', kittySchema);
Kitten.create({ name: "mike" }, function (err, small) {
if (err) return handleError(err);
});
Kitten.findOne( { } ), function(err, docs){
console.log(docs.name);
};
return 1;

newKitten = { name: "mike" };
Kitten.create(newKitten, function (err, kitty) {
if {
(err) return handleError(err);
} else {
console.log(kitty); //OR console.log(kitty.name);
}
});
Kitten.findOne({name: "mike"}).exec(function(e, kitten) {
if (e) {
console.log(e)
} else {
console.log(kitten.name)
}
});

the problem was {for anyone whose intersted (and thanks for herkou)} that I did not use the exec command..
This works:
Kitten.findOne( { name: "mike"} ).exec( function(err, docs){
console.log(docs.name);
return;
});
update:
also had a probelm with race conditions... the create of the documnet not finished when the query was called. that is why I got undeinfed.
use this new code:
var mongoose = require('mongoose');
var url = 'mongodb://Yotam:Yotam#ds023475.mlab.com:23475/small-talkz';
mongoose.connect(url);
var kittySchema = mongoose.Schema({
name: String,
color:String
});
var Kitten = mongoose.model('Kitten', kittySchema);
var newKitten = { name: "mike", color:"white" };
Kitten.create(newKitten, function (err, kitty) {
if (err) {
return handleError(err);
} else {
call_query();
}
});
var call_query= function(){
var query= Kitten.findOne( { name: "mike"} );
query.exec( function(err, docs){
console.log(docs.color);
return;
});
}
return 1;
now I just need to understand why this script doesn't end.

Related

Nodejs Mongodb - Document Property is 'Undefined ' when printing

I'm learning Node, Express & Mongodb, hence a very much beginner. I'm developing a form where in there is a text field in which user will add data.
First, i need to check if that data exist or not in a master table. If exist, then i will return the record id else i will create a new record and return its id. Below is the code which I had tried but it's giving me id as undefined.
code.js (controller)
const toolsModel = require('../models/modTools');
const { validationResult } = require('express-validator');
module.exports = {
async saveCode(req, res)
{
var promiseToolId = () => {
return new Promise((resolve, reject) => {
let tool_exist = toolsModel.findOne({ title: req.body.inpTool });
if (tool_exist) {
console.log('tool_exist'); // prints this line
console.log(tool_exist._id); // gives undefined
console.log(tool_exist); // prints the object.
resolve(tool_exist._id);
}
else{
console.log('tool not exist. inserting');
var newTool = new toolsModel();
newTool.insert({title: req.body.inpTool, created_at: new Date()}, function(err, newRec) {
if(err){
console.log('err while inserting');
console.log(err);
reject(err);
}
else{
console.log('inserted');
console.log(newRec);
resolve(newRec._id);
}
});
}
});
};
let errors = validationResult(req);
if (!errors.isEmpty()){
console.log('validation error');
console.log(errors);
}
else{
console.log('form is valid'); // prints this line
// check if the tool exists in our database
var toolId = await (promiseToolId()); //anything here is executed after result is resolved
console.log('toolId ', toolId); // prints undefined
}
}
};
modTools.js (model)
const mongoose = require('mongoose'),
timeZone = require('mongoose-timezone'),
Schema = mongoose.Schema;
const toolsSchema = new Schema({
title: {type:String, required:true, trim: true},
created_at: {type: Date, default: Date.now},
});
toolsSchema.plugin(timeZone);
module.exports = mongoose.model('developmentTools', toolsSchema);
Please note that I'm using Auto-increment id for my model above which i had created using below codes.
db.createCollection("developmentTools");
db.developmentTools.insert ( {_id: "toolsId" , toolSeqValue : 0 } );
function getToolsNextID(seqName) {
var seqDoc = db.developmentTools.findAndModify({
query: { _id: seqName },
update: { $inc: { toolSeqValue: 1 } },
new: true
});
return seqDoc.toolSeqValue;
}
I know the way I'm accessing the object property tool_exist.title is correct but dont know why its giving me undefined.
M I wrong in implemenation of the Promise?
Please help.
Much Regards,
Javed Ansari
I'm able to resolve the issue. Listing the complete code if anyone faces the same issue. Thanks a lot to #ifaruki for sharing the informative URL and #slimane-amiar for his time.
async saveCode(req, res)
{
async function createTool(tool_ttle){
var newTool = new toolsModel({
title: tool_ttle,
created_at: new Date()
});
return new Promise((resolve, reject) => {
newTool.save((err, newRec) => {
if(err){
console.log('err while inserting');
reject(err);
}
else{
console.log('inserted');
resolve(newRec);
}
});
});
}
let errors = validationResult(req);
if (!errors.isEmpty()){
console.log('validation error');
console.log(errors);
}
else{
console.log('form is valid');
toolTitle = req.body.inpTool;
toolTitle = toolTitle.trim().toUpperCase();
let toolRecord = '';
// check if the tool exists in our database
try {
toolRecord = await toolsModel.findOne({ title: toolTitle });
if (toolRecord){
console.log('tool_exist');
console.log(toolRecord);
}
else{
console.log('tool not exist. inserting');
toolRecord = await createTool(toolTitle);
if(toolRecord){
console.log('new tool is created below');
console.log(toolRecord);
}
else
{
console.log('error in creating new tool');
console.log(toolRecord);
}
}
}
catch(error){
console.log('in catch');
console.log(error);
return error;
}
console.log('proceeding further');
}
}
You should add await to the query as it returns a promise, as follow
return new Promise( async (resolve, reject) => {
let tool_exist = await toolsModel.findOne({ title: req.body.inpTool });

How to retrieve and add the value from one collection to another.. Mongoose , Node JS

Asset and Assetlist are two different collection. If a assetlist got created i want to add the quantity of the assetlist to asset quantity. Could anyone please suggest how to achieve this..
app.post("/assetlists/new", function(req, res){
var astname = req.body.astname;
var brand = req.body.brand;
var quantity1 = req.body.quantity;
var purchasedate = req.body.purchasedate;
var newAssetlist = {astname: astname, brand: brand, quantity: quantity, purchasedate: purchasedate};
Assetlist.create(newAssetlist, function(err, newlyCreated){
if(err){
console.log(err);
} else{
res.redirect("/assetlists");
console.log("Working create");
}
});
Asset.findOneAndUpdate({ name: astname }, {$set:{ quantity: quantity1}}, function(err, updatedAssetquantity){
if(err){
console.log(err);
} else {
}
});
});
Try this code:
Here we are using $inc in the update query. The Update query is called in the callback after the creation of a AssetList.
app.post("/assetlists/new", function (req, res) {
var astname = req.body.astname;
var brand = req.body.brand;
var quantity1 = req.body.quantity;
var purchasedate = req.body.purchasedate;
var newAssetlist = {astname: astname, brand: brand, quantity: quantity, purchasedate: purchasedate};
Assetlist.create(newAssetlist, function (err, newlyCreated) {
if (err) {
console.log(err);
} else {
console.log("Working created", newlyCreated);
Asset.findOneAndUpdate({name: astname}, {$inc: {quantity: 1}}, function (err, updatedAssetquantity) {
if (err) {
console.log(err);
} else {
console.log("updatedAssetquantity", updatedAssetquantity);
res.redirect("/assetlists");
}
});
}
});
});
Hope this helps you.

$addToSet to an array but it gives me null

so basically I've a wish list and I've bunch of products that I want to add inside the the wish list products array using a put request (I'm using postman btw).
This is the wish list schema, and yes I know that the document's name in the db is "whishlist"....I hate typos
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var whishList = new Schema({
title: {type: String, default: "Cool whishlist"},
products:[{type: ObjectId, ref:'Product'}]
});
module.exports = mongoose.model('WhishList', whishList);
This is the products schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var product = new Schema({
title: String,
price: Number,
likes: {type: Number, default: 0}
});
module.exports = mongoose.model('Product', product);
and now this is the code that I am trying to run
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/swag-shop');
var Product = require('./model/product');
var wishList = require('./model/wishlist');
app.put('/wishlist/product/add', function(request, response){
Product.find({_id: request.body.productId}, function(err, product){
if(err) {
response.status(500).send({err: "could not add item to wishlist"});
}else{
wishList.update({_id: request.body.wishlistId},{$addToSet: {products: product._id}}, function(err, wishlist){
if(err){
response.status(500).send({err: "could not add item to wishlist /update/"});
}else{
response.send(wishlist);
}
});
}
});
I really can't see where is the problem I tried deleting the document and posting it again but I had the same problem.
Thanks in advance
The issue is that the result from Product.find() is an array of Mongoose documents if the query matches any documents in the collection instead of a single document which you want.
Thus the expression {$addToSet: {products: product._id}} resolves to {$addToSet: {products: undefined}} because product is an array and product._id is undefined. Take this simple example
var product = [{ '_id': 1 }];
console.log(product._id) // logs undefined
To remedy this problem, you can either access the only element in the array as
wishList.update(
{ '_id': request.body.wishlistId },
{ '$addToSet': { 'products': product[0]._id} },
function(err, wishlist) { ... }
);
Or use the findOne() method which returns a single document when querying the product:
Product.findOne({ '_id': request.body.productId }, function(err, product) {
if(err) {
response.status(500).send({err: "could not add item to wishlist"});
} else {
wishList.update(
{ '_id': request.body.wishlistId },
{ '$addToSet': { 'products': product._id } },
function(err, wishlist) { ... }
);
}
});
The findById() method is also useful in this case i.e.
Product.findById(request.body.productId, function(err, product) {
if(err) {
response.status(500).send({err: "could not add item to wishlist"});
} else {
wishList.update(
{ '_id': request.body.wishlistId },
{ '$addToSet': { 'products': product._id } },
function(err, wishlist) { ... }
);
}
});

How to update document field in mongodb?

I am new to Mongodb so below code i am trying to update document field string i have object recieved in post req.body now based on _id i want to update string field but it is not updating record with below implementation. How can i update record using _id ? Any better approach to update record in terms of async will be appreciated.
routes.js
var Diagram = require('./diagram');
router.post('/saveUpdateDiagram',function(req,res){
console.log(req.body._id);
Diagram.update(req.body);
});
diagram.js
var diagram = require('./diagram.model');
var mongoose = require('mongoose');
var Diagram = {
index: function(callback) {
diagram.find({}, function(err, result) {
if (!err) {
callback(result);
}
});
},
update: function(data) {
console.log('data in controller', data);
Diagram.update({ $set: { 'string' : data.string } });
}
}
module.exports = Diagram;
data.json
{
_id: "57fe42efc3590c7686bad563"
groups: Array[0]
owner: "sh587"
string: "test string should be updated"
text: "gcs_wf_dit.bpmn"
users: Array[1]
}
We know that JavaScript is case sensitive language you should use diagram.update not Diagram.update
use `diagram.update({ $set: { 'string' : data.string } });
diagram.js should be
diagram.js
var diagram = require('./diagram.model');
var mongoose = require('mongoose');
var Diagram = {
index: function(callback) {
diagram.find({}, function(err, result) {
if (!err) {
callback(result);
}
});
},
update: function(data) {
console.log('data in controller', data);
diagram.update({_id: data._id}, { $set: { 'string' : data.string } });
}
}
module.exports = Diagram;
Make sure you have "string" field in diagram model. as mongoose allow only those fields which are available in schema. If not then add
string: {type: String}
and then use
var diagram = require('./diagram.model');
var mongoose = require('mongoose');
var Diagram = {
index: function(callback) {
diagram.find({}, function(err, result) {
if (!err) {
callback(result);
}
});
},
update: function(data) {
diagram.update({_id: data._id}, { $set: { 'string' : data.string } });
}
}
module.exports = Diagram;

Find() function retunrs undefined - Mongoose and Node.js

I was trying to do a simple function with Node.js and Mongoose that returns true if the model is empty.
The mongoose configuration is fine:
var mongoose = require('mongoose');
var db = mongoose.createConnection( 'mongodb://localhost:27017/prueba' );
var userSchema = mongoose.Schema({
phoneNumber: Number,
name: String
});
var User = db.model('User', userSchema, 'User'');
Then I tried to do this:
User.find(function(err, data) {
if (err) {console.log(err)};
console.log(data.length == 0 );
});
And it works fine, it logs true, or false.
Then I tried to do:
var isUsersEmpty = function () {
User.find(function(err, data) {
if (err) {console.log(err)};
console.log(data.length == 0);
});
}
isUsersEmpty();
And again it works fine, it logs true or false, buy if I do:
var isUsersEmpty2 = function () {
User.find(function(err, data) {
if (err) {console.log(err)};
return data.length == 1;
});
}
console.log(isUsersEmpty2());
Then the log prints "Undefined".
What can I do if I need a function that returns true or false to do things like this:
if (isUsersEmpty2()) {} //Do something here...
And isUsersEmpty2() returns always undefined.
isUsersEmpty2() returns a promise , which means you can't just log it like you did. You need to send a response from the function. This should work:
var isUsersEmpty2 = function (res) {
User.find(function(err, data) {
if (err) res(err, null);
res(null, data.length == 1);
});
}
isUsersEmpty2(function(err, res) {
if(res) {/*do something*/}
});

Categories