populate query does not show newly added referenced item - node.js

My schema is as follows:
items.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ItemSchema = new Schema({
no_of_times_ordered:Number,
item_name:String,
item_tag:String,
item_category:String,
item_illustrations:[String],
item_stock:Number, //0 available 1 last 5 items 2 not available
item_quantity_ordered:{type:Number,default:0},
item_discount_price:Number,
item_price:Number,
item_img:String,
no_of_likes:{type:Number,default:0}
},{ versionKey: false });
module.exports = mongoose.model('items',ItemSchema);
foodtruck.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Items = require('./items.js');
var FoodTruckSchema = new Schema({
foodtruck_name:String,
foodtruck_location:String,
foodtruck_rating:{type:Number,default:5},
foodtruck_total_votes:{type:Number,default:0},
foodtruck_tag:String,
foodtruck_open_status:{type:Number,default:1}, //0 open 1 closed
foodtruck_starting_timing:String,
foodtruck_closing_timing:String,
foodtruck_cusine:String,
foodtruck_img:String,
foodtruck_logo:String,
item_list: [ {type : mongoose.Schema.ObjectId, ref : 'items'}]
},{ versionKey: false });
module.exports = mongoose.model('foodtruck',FoodTruckSchema);
My query is as below:
var addItem = function(req, res) {
var foodtruck_id = req.body.foodtruck_id;
var newItem = new item();
var itemList = [];
newItem.item_name = req.body.item_name;
newItem.item_tag = req.body.item_tag;
newItem.item_category = req.body.item_category;
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
if (key == 'item_illustrations') {
newItem.item_illustrations = req.body[key];
}
}
}
newItem.item_stock = req.body.item_status;
newItem.item_price = req.body.item_price;
if ((foodtruck_id) && (foodtruck_id.trim() != '')) {
foodtruck.findById(foodtruck_id.trim(), function(err, foodtrucks) {
if (err)
res.json({
status: '500',
message: 'There is no data available'
});
newItem.save(function(err, savedItem) {
if (!err) {
foodtrucks.item_list.push(savedItem._id);
foodtrucks.save();
foodtruck.find({
_id: foodtruck_id.trim()
}).populate('item_list').exec(function(err, foodtrucks) {
res.json({
status: '200',
message: 'New item added successfully',
data: foodtrucks
});
});
} else {
res.json({
status: '500',
message: 'Error while saving new item'
});
}
});
});
}
}
The main problem I am facing is that, I am able to create new item ,add its reference to the foodtruck schema, but somehow when I put populate query for the same foodtruck, the newly created item does not show. So,can you tell me how exactly I can show this item via populate query?

I think you got to put the populate inside the save function to make the populate method happen after the save.
foodtrucks.save(function(err, doc) {
//do population here
});
using asynchronous methods.

Related

Mongoose is only returning ID from MongoDB

I am currently trying to incorporate datatables with my MongoDB database. I am having some trouble accessing the returned object though. The main problem I am seeing is that I am only getting the _id returned from MongoDB, and no values of the object.
Heres the code I am using to pass the information to the datatables.
var itemsModel = require('./models/itemReturn');
exports.getItemList = function(req, res) {
var searchStr = req.body.search.value;
if (req.body.search.value) {
var regex = new RegExp(req.body.search.value, "i")
searchStr = { $or: [{ 'productName': regex }, { 'itemPrice': regex }, { 'Quantity': regex }, { 'Description': regex }, { 'seller': regex }] };
} else {
searchStr = {};
}
var recordsTotal = 0;
var recordsFiltered = 0;
itemsModel.count({}, function(err, c) {
recordsTotal = c;
console.log(c);
itemsModel.count(searchStr, function(err, c) {
recordsFiltered = c;
itemsModel.find(searchStr, 'productName itemPrice Quantity Description seller', { 'skip': Number(req.body.start), 'limit': Number(req.body.length) }, function(err, results) {
if (err) {
console.log('error while getting results' + err);
return;
}
var data = JSON.stringify({
"draw": req.body.draw,
"recordsFiltered": recordsFiltered,
"recordsTotal": recordsTotal,
"data": results
});
console.log(data);
res.send(data);
});
});
});
};
This is the model
// app/models/itemsReturn.js
// load the things we need
var mongoose = require('mongoose');
var schemaOptions = {
timestamps: true,
toJSON: {
virtuals: true
},
toObject: {
virtuals: true
}
};
// define the schema for our item model
var itemsReturned = mongoose.Schema({
productName: String,
itemPrice: String,
Quantity: String,
Description: String,
seller: String
}, schemaOptions);
// create the model for users and expose it to our app
var items = mongoose.model('items', itemsReturned);
module.exports = items;
The thing is that I know its not a data table issue as I can make the _id appear in the tables. I just need to know how to return the entire object instead of just the _ID so that I can access the values of the object.
If it helps this is the tutorial I am following.
UPDATE: Okay so I figured out why my MongoDB collections were only returning the item ID. The issue was that I had stored everything in the local database (oops).

Mongoose: Saving ref of another document into an array of objects document returns empty array

I'm trying to add specific document's ref id into another document's array of object. So that I can use populate method. But somehow the array remains empty even after pushing the ref.
Please help me. Thank you in advance.
Here is list.js:
const mongoose = require('mongoose');
const User = require('./user');
const Task = require('./task');
const Schema = mongoose.Schema;
// User Schema
const ListSchema = mongoose.Schema({
item:{
type: String,
required: true
},
purpose:{
type: String,
required: true
},
user: {
type: Schema.ObjectId,
ref:"User"
},
deadline:{
type: Date,
default: null
}
});
const List = module.exports = mongoose.model('List', ListSchema);
task.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const List = require('./list');
// User Schema
const TaskSchema = mongoose.Schema({
task:{
type: String,
required: true
},
list: [{
type: Schema.Types.ObjectId,
ref:'List'
}]
});
const Task = module.exports = mongoose.model('Task', TaskSchema);
Here is how I create and save new task instance:
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
let List = require('../models/list');
let User = require('../models/user');
let Task = require('../models/task');
router.post('/add', isAuthenticated, function(req,res){
var tasker = req.body.task, listshash= [];
var startIndex = 0, index;
var x,y,listid= [];
while ((index = tasker.indexOf("#", startIndex)) > -1) {
var ind = tasker.indexOf(" ", index);
if(ind == -1)
listshash.push(tasker.substring(index+1));
else
listshash.push(tasker.substring(index+1,ind));
startIndex = index + 1;
}
//Instance of task
var taskIns = new Task({task: req.body.task});
List.find({user: req.session.passport.user}, function(err, lists){
for(x in lists){
for(y in listshash){
if(lists[x].item.toLowerCase().replace(/\s/g,'') == listshash[y]){
//lists[x] contains the document "list" that I want to store as
//ref in list property array of task
taskIns.list.push(lists[x]);
//console.log(taskIns.list.push(lists[x]));
}
}
}
});
taskIns.save(function(err, doc){
if(err) res.json(err);
else {
console.log("Saved");
res.redirect('/lists');
}
});
});
module.exports = router;
This is how the database collection of tasks look like after inserting data:
See the data
You should have to use async npm
List.find({user: req.session.passport.user}, function(err, lists){
async.each(lists ,function(x,callback){
async.each(listhash, function(y,callback){
if(x.item.toLowerCase().replace(/\s/g,'') == y){
taskIns.list.push(x);
}
});
});
//After that you can do save the data
taskIns.save(function(err, doc){
if(err) res.json(err);
else {
console.log("Saved");
res.redirect('/lists');
}
});
});
It's not saving the refs because you are dealing with asynchronous functions; you are pushing the lists within the find() callback and the taskIns model save event happens before the push.
You can move the taskIns save operation within the find() callback or use promises to tackle the issue.
For example, using callbacks:
List.find({ user: req.session.passport.user}, (err, lists) => {
const taskIns = new Task({task: req.body.task});
for(x in lists) {
for(y in listshash) {
if(lists[x].item.toLowerCase().replace(/\s/g,'') == listshash[y]) {
taskIns.list.push(lists[x]);
}
}
}
taskIns.save((err, doc) => {
if(err) res.json(err);
else {
console.log("Saved");
res.redirect('/lists');
}
});
});

how to add referenced item in collection in mongoose

items.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ItemSchema = new Schema({
no_of_times_ordered:Number,
item_name:String,
item_tag:String,
item_category:String,
item_illustrations:[String],
item_stock:Number, //0 available 1 last 5 items 2 not available
item_quantity_ordered:{type:Number,default:0},
item_price:Number,
item_img:String,
no_of_likes:{type:Number,default:0}
},{ versionKey: false });
module.exports = mongoose.model('items',ItemSchema);
foodtruck.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Items = require('./items.js');
var FoodTruckSchema = new Schema({
foodtruck_name:String,
foodtruck_location:String,
foodtruck_rating:{type:Number,default:5},
foodtruck_total_votes:{type:Number,default:0},
foodtruck_tag:String,
foodtruck_timing:String,
foodtruck_cusine:String,
foodtruck_img:String,
foodtruck_logo:String,
item_list: [ {type : mongoose.Schema.ObjectId, ref : 'items'}]
},{ versionKey: false });
module.exports = mongoose.model('foodtruck',FoodTruckSchema);
item_list_foodtruck.js
var addItem = function(req,res) {
var foodtruck_id = req.body.foodtruck_id;
var newItem = new item();
var itemList=[];
newItem.item_name = req.body.item_name;
newItem.item_tag = req.body.item_tag;
newItem.item_category = req.body.item_category;
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
if(key =='item_illustrations'){
newItem.item_illustrations = req.body[key];
}
}
}
newItem.item_stock = req.body.item_status;
newItem.item_price = req.body.item_price;
if((foodtruck_id)&&(foodtruck_id.trim()!='')) {
foodtruck.findById(foodtruck_id.trim(),function (err, foodtrucks) {
if (err)
res.json({
status:'500',
message:'There is no data available'
});
newItem.save();
foodtrucks.item_list.push(newItem);
foodtrucks.save();
foodtruck.findById(foodtruck_id.trim()).populate('item_list').exec(function (err, foodtrucks) {
if (err) res.json({
status:'500',
message:'There is no data available'
});
res.send({
status:'200',
message:'Review List',
data:foodtrucks
});
});
});
}
else {
res.json({
status:'404',
message:'Please enter valid foodtruck id'
});
}
};
Here actually items is referenced document in foodtruck collection.so here items are added to items array, but somehow they are not updating their reference in foodtruck.item_list
.

Mongoose not returning document from mongo

I am trying to get Mongoose to query my mongo instance for a specific document (using the _id attribute). I currently have the following route:
router.get('/document/', function (req, res) {
var getDocuments = function (callback) {
var options = { server: { socketOptions: { keepAlive: 1000 } } };
var connectionString = 'mongodb://user:password#server:27017/db';
var pID = req.query.id;
pID = pID.trim();
console.log(pID);
var documentArray = [];
// Connected handler
Mongoose.connect(connectionString, function (err) {
var db = Mongoose.connection.useDb('db');
var pCollection = db.collection("collection");
//grab all items from pCollection
pCollection.find({ '_id': pID }, function (error, pDocument) {
if (error) {
console.log(error);
}
if (pDocument) {
// res.send(JSON.stringify(pDocument));
console.log(pDocument);
}
else {
console.log("nothing");
}
});
db.close();
});
};
getDocuments(function () {
});
});
The result returned is not a json document and does not seem to return a usable value. What am I doing wrong? Thanks for any help in advance!
EDIT:
I went back and changed the route to the following:
router.get('/document/', function (req, res) {
var pID = req.query.id;
pID = pID.trim();
console.log(pID);
Document.findById(pID, function (error, document) {
if (error) {
console.log(error);
}
else {
console.log(document);
}
});
});
I also created the following model:
var mongoose = require('mongoose');
var DocumentSchema = require('../schemas/documents');
var Document = mongoose.model('documents', DocumentSchema, 'Documents');
module.exports = Document;
And used the following schema:
var mongoose = require('mongoose');
var DocumentSchema = new mongoose.Schema({
documenttPK: String,
locationID: String,
docName: String,
SerialNumber: String,
documentID: String,
dateEntered: Date,
activeFlag: Boolean
});
module.exports = DocumentSchema;
My app.js makes a single call to a db file:
var mongoose = require('mongoose');
mongoose.connect('mongodb://user:password#server:27017/db');
But the result is still null. Is something wrong with the above code?

Mongoose nested document update failing?

If I have a nested document, how can I update a field in that nested document in Mongoose?
I carefully researched this problem using everything available I could find, and even changed my test code to match a similar answered question about this here on Stackoverflow, but I am still unable to figure this out. Here are is my Schema and Models, the code, and the Mongoose debug output. I am unable to understand what I am doing wrong, here.
var mongoose = require('mongoose')
, db = mongoose.createConnection('localhost', 'test')
, assert = require("node-assert-extras");
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
db.once('open', function () {
// yay!
});
mongoose.set('debug', true);
var PDFSchema = new Schema({
title : { type: String, required: true, trim: true }
})
var docsSchema = new Schema({
PDFs : [PDFSchema]
});
var A = db.model('pdf', PDFSchema);
var B = db.model('docs', docsSchema);
function reset(cb) {
B.find().remove();
// create some data with a nested document A
var newA = new A( { title : "my title" })
var newB = new B( { PDFs: newA});
newB.save();
cb();
}
function test1( ) {
reset(function() {
B.findOne({}, 'PDFs', function(e,o)
{
console.log(o);
pdf_id = o.PDFs[0]._id;
console.log("ID " + pdf_id);
B.update(
{ 'pdfs.pdf_id': pdf_id },
{ $set: {
'pdfs.$.title': 'new title'
}}, function (err, numAffected) {
if(err) throw err;
assert.equal(numAffected,1); //KA Boom!
}
);
});
});
}
test1();
/*
$ node test2.js
Mongoose: docs.remove({}) {}
Mongoose: docs.findOne({}) { fields: { PDFs: 1 }, safe: true }
Mongoose: docs.insert({ __v: 0, PDFs: [ { _id: ObjectId("50930e3d0a39ad162b000002"), title: 'my title' } ], _id: ObjectId("50930e3d0a39ad162b000003") }) { safe: true }
{ _id: 50930e3d0a39ad162b000003,
PDFs: [ { _id: 50930e3d0a39ad162b000002, title: 'my title' } ] }
ID 50930e3d0a39ad162b000002
assert.js:102
throw new assert.AssertionError({
^
AssertionError: 0 == 1
*/
You're not using the correct field names in your B.update call. It should be this instead:
B.update(
{ 'PDFs._id': pdf_id }, // <== here
{ $set: {
'PDFs.$.title': 'new title' // <== and here
}}, function (err, numAffected) {
if(err) throw err;
assert.equal(numAffected,1);
}
);
You should also fix your reset function to not call its callback until the save completes:
function reset(cb) {
B.find().remove();
// create some data with a nested document A
var newA = new A( { title : "my title" })
var newB = new B( { PDFs: newA});
newB.save(cb); // <== call cb when the document is saved
}

Resources