Issue in document insert using mongoose - javascript

I have schema created now i want to insert into mongodb collection, but its throwing error diagramModel.insert is not defined any idea what is implemented wrong ?
app.js
mongoose.connect('mongodb://localhost:27017/develop-modeler');
require('./server/api/diagram/diagram.model.js');
var diagramModel = mongoose.model('Diagram');
var newDiagram = {
"owner" : "sh529u",
"text" : "sco_poc.bpmn",
"users":["wp6307","kz323j","ew6980"],
"groups":[],
"string" : "test"
}
mongoose.connection.on('connected', function () {
diagramModel.insert(newDiagram,function(err,res){
if (err) { console.log(err);}
else {
diagramModel.find({}, function(err, data) { console.log(data);});
}
});
});
diagram.model.js
var DiagramSchema = new mongoose.Schema({
text: String,
owner: {type: String, ref:'User'},
groups: [{type: String, ref: 'Group'}],
users: [{type: String, ref: 'User'}],
string: String
});
mongoose.model('Diagram', DiagramSchema);

I think it's save not insert while saving records. That's why you are getting this error
mongoose.connect('mongodb://localhost:27017/develop-modeler');
var diagramModel = require('./server/api/diagram/diagram.model.js');
var newDiagram = {
"owner": "sh529u",
"text": "sco_poc.bpmn",
"users": ["wp6307", "kz323j", "ew6980"],
"groups": [],
"string": "test"
}
mongoose.connection.on('connected', function() {
diagramModel.save(newDiagram, function(err, res) {
if (err) {
console.log(err);
} else {
diagramModel.find({}, function(err, data) {
console.log(data);
});
}
});
});
var DiagramSchema = mongoose.Schema({
text: String,
owner: {type: String, ref:'User'},
groups: [{type: String, ref: 'Group'}],
users: [{type: String, ref: 'User'}],
string: String
});
module.exports=mongoose.model('Diagram', DiagramSchema);

Create a new instance of your model and this instance contains a save method:
mongoose.connect('mongodb://localhost:27017/develop-modeler');
require('./server/api/diagram/diagram.model.js');
var diagramModel = mongoose.model('Diagram');
var newDiagram = new diagramModel({
"owner" : "sh529u",
"text" : "sco_poc.bpmn",
"users":["wp6307","kz323j","ew6980"],
"groups":[],
"string" : "test"
});
mongoose.connection.on('connected', function () {
newDiagram.save(function(err,res){
if (err) { console.log(err);}
else {
diagramModel.find({}, function(err, data) { console.log(data);});
}
});
});

Try this its working perfect
var diagramModel = require('./server/api/diagram/diagram.model.js');
var finalDiagram = diagramModel({
"owner" : "sh529u",
"text" : "sco_poc.bpmn",
"users":["wp6307","kz323j","ew6980"],
"groups":[],
"string" : "test"
});
mongoose.connection.on('connected', function () {
finalDiagram.save(function (err, dataObj) {
if (err) { console.log(err);}
} else {
console.log("DATA",dataObj);
diagramModel.find({}, function(err, data) { console.log(data);});
}
});
});

Related

How to access array elements that are defined in another array of Mongoose scheme object Array?

This is the User schema in mongoose:
var userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
},
name: {
type: String,
required: true,
},
Addtasks: [
{
topic: String,
words: Number,
keywords: String,
website: String,
otherdetails: String,
exampleRadios: String,
deadline: Date,
Date: String,
fileName: String,
Bigpaths: [],
},
],
});
module.exports = mongoose.model('User', userSchema);
I want to use/access the Bigpaths array, which is defined inside the Addtasks array, which is defined in User. Data is already are there in mongoDB, which I have inserted via UI page. I am trying the following code but I am getting this error in console:
data.Addtasks[Object.keys(data.Addtasks).length - 2].Bigpaths.forEach(
(element) => {
// ...
}
)
as
TypeError: Cannot read property 'Bigpaths' of undefined
at \Desktop\grumpytext\routes\index.js:99:71
Code:
const { files } = req;
User.findOne({ email: req.user.email }, function (error, data) {
if (error) {
console.log('Three');
} else if (data) {
if (Object.keys(data.Addtasks).length > 1) {
data.Addtasks[Object.keys(data.Addtasks).length - 2].Bigpaths.forEach(
(element) => {
files.forEach((currentElement) => {
if (element.name == currentElement.filename) {
files.pull(currentElement.filename);
}
});
}
);
}
}
});
How to resolve this error or how to access all the elements of Bigpaths array so that I can iterate it with forEach loop?
I'm not sure here, but I think you need to populate Addtasks prior to manipulating it:
const files = req.files;
User.findOne({email:req.user.email}).populate('Addtasks').exec((error, data) => {
if (error) {
console.log("Three");
}
else
{
if(data)
{
if(Object.keys(data.Addtasks).length > 1)
{
console.log("Addtasks count: " + Object.keys(data.Addtasks).length);
data.Addtasks[Object.keys(data.Addtasks).length - 2].Bigpaths.forEach(element => {
files.forEach(currentElement => {
if(element.name == currentElement.filename)
{
files.pull(currentElement.filename);
}
})
});
}
}
}
});
Please notice the log console.log("Addtasks count: " + Object.keys(data.Addtasks).length); - in case the solution does not work, I advise to add some prints, especially to check if the count of elements is as expected or properties within an object are fine.

mongoose findOneAndUpdate deletes nested vars

In my express/mongoose code when I update a nested var it deletes any other nested vars in the object I didn't update?
My schema:
var MySchema = new Schema({
active: { type: Boolean, required: true, default: true },
myvar: {
useDefault: { type: Boolean, required: true },
custom: { type: String },
default: { type: String }
}
});
My express middleware update function:
var updateData = req.body;
MySchema.findOneAndUpdate({ active: true }, updateData, function(err, myschema) {
if (err) throw err;
if (!myschema) { response(403, { success:false, message: "myschema not updated." }, res); }
// success
response(200, { success:true, message: "myschema updated." }, res);
});
The record initially look like this:
{
"myvar": {
"useDefault": true,
"custom": "some custom var",
"default": "some value"
}
}
When I submit an update to say the myvar.useDefault value the record ends up like this:
{
"myvar": {
"useDefault": false
}
}
Can anyone advise how to update only the targeted var and leave any other vars as they were?
The answer was to convert the response.body object to dot notation and pass that modified object to mongoose findOneAndUpdate. Thanks to #btkostner on Gitter for the answer and his toDot function. Here is the relevant bits of code:
function(req, res) {
// convert response to dot notation so objects retain other values
var dotData = toDot(req.body, '.');
MySchema.findOneAndUpdate({ active: true }, dotData, function(err, myschema) {
...
}
// author: #btcostner
function toDot (obj, div, pre) {
if (typeof obj !== 'object') {
throw new Error('toDot requires a valid object');
}
if (pre != null) {
pre = pre + div;
} else {
pre = '';
}
var iteration = {};
Object.keys(obj).forEach(function(key) {
if (_.isPlainObject(obj[key])) {
Object.assign(iteration, _this.toDot(obj[key], div, pre + key));
} else {
iteration[pre + key] = obj[key];
}
});
return iteration;
};
NOTE: I had to convert the toDot() function to ES5 for my project, here is the original ES6 version: github.com/elementary/houston/blob/master/src/lib/helpers/dotNotation.js

Populate not working for an array of ObjectIDs

This is the implementation of my models :
var itemSchema = new Schema({
name : String,
qte : Number
});
var Item = mongoose.model('Item', itemSchema);
var orderSchema = new Schema({
state : {
type: String,
enum: ['created', 'validated', 'closed', 'starter', 'meal', 'dessert'],
required : true
},
table : {
number : {
type : Number,
required : true
},
name : {
type : String,
required : false
}
},
date: { type: Date, default: Date.now },
_items : [{type:Schema.Types.ObjectId, ref:'Item'}]
});
And this is how I do my query
getByIdRaw : function (orderId, callback) {
Order.findById(orderId)
.populate('_items')
.exec(function(err, order) {
debug(order);
callback(order);
});
}
This is my response without populating
{
_id: "5549e17c1cde3a4308ed70d5"
state: "created"
_items: [1]
0: "5549e1851cde3a4308ed70d6"
-
date: "2015-05-06T09:40:12.721Z"
table: {
number: 1
}-
__v: 1
}
...and my response when populating _items
{
_id: "5549e17c1cde3a4308ed70d5"
state: "created"
__v: 1
_items: [0]
date: "2015-05-06T09:40:12.721Z"
table: {
number: 1
}-
}
Why the _items array is empty ? What am I doing wrong ?
EDIT : the addItem function
addItem : function (orderId, item, callback) {
Order.findById(orderId)
.exec(function(err, order) {
if (err) {
error(err);
return callback(err);
}
if (order === null) {
return callback("No order with this id");
}
var newItem = new Item({
name : item.name,
qte :item.qte
});
order._items.push(newItem);
order.markModified('_items');
order.save();
callback();
});
}
The issue is the new item is never persisted to the items collection. Mongoose references only populate they don't persist a new item to the referenced collection.
addItem: function(orderId, item, callback) {
var newItem = new Item({
name: item.name,
qte: item.qte
});
newItem.save(function(err, savedItem) {
if (err) {
error(err);
return callback(err);
}
Order.findById(orderId).exec(function(err, order) {
if (err) {
error(err);
return callback(err);
}
if (order === null) {
return callback("No order with this id");
}
order._items.push(savedItem);
order.markModified('_items');
order.save(callback);
});
});
}

Why my mongoose objectId request return an empty array?

I past my day to find the answer, in vain.
this is my mongoose schema:
var schema = new mongoose.Schema({
value: {type: String},
title: {type: String},
date: { type: Date, default: Date.now },
packId: {type: mongoose.Schema.Types.ObjectId, ref:'Pack'}
});
this is my request:
( Where packId is a ObjectId )
var getElements = function(packId, callback ){
Card.find(
{packId: packId},
function(err,els){
if(err){
console.log(err);
}else{
console.log(els);
}
}
);
};
**And this is a table element **
{
"title" : "test1",
"value" : "test1",
"packId" : ObjectId("54f9ebaae312727c45b2a80e"),
"_id" : ObjectId("54f9ebaae312727c45b2a820"),
"date" : ISODate("2015-03-06T18:02:18.544Z"),
"__v" : 0
}
I don't understand why the console.log(els) return [], because there is elements in table. I've tried whith {type: Sting} but nothing at all.
Thanks
OK, i've found the reason.
models.Card.saveCards(completeData.cards,packData.cid, function(){
models.Card.getCards(packData.cid,function(cards){
...
}
}
the second method getCards is called before all cards are saved.
So this is how i did
var saveCards = function( cardsData, packId, callback ){
var nbCards = cardsData.length;
var start = 0;
var saveCard = function(cardData,packId) {
cardData.packId = packId;
var card = new Card(cardData);
card.save(function (err, card) {
if (err) {
console.log(err);
} else {
if(start<nbCards-1){
start++;
saveCard(cardsData[start],packId);
}else{
callback();
}
}
});
};
if( start === 0){
saveCard(cardsData[start],packId);
}
};
hope this helps

Add more fields in MapReduce with Mongoose and NodeJS

I've this mongoose schema
var SessionSchema = mongoose.Schema({
id: Number,
cure: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Cure'
},
performances: Array,
startDate: Date,
endDate: Date,
validatee: Boolean,
deleted: Boolean
});
I need to know how many documents have different ids, but i only need those that have startDate greater than a given date (for example today).
Running the following code works fine but i want to add some fields in map to use them in the query.
var o = {};
o.map = function () {
emit(this.id, 1
// list other fields like above to select them
)
}
o.reduce = function (k, vals) {
return vals.length
}
o.out = {
replace: 'createdCollectionNameForResults'
};
o.verbose = true;
Session.mapReduce(o, function (err, model, stats) {
console.log('map reduce took %d ms', stats.processtime)
console.log("MapReduce" + JSON.stringify(model));
model.find().exec(function (err, docs) {
console.log(docs);
});
});
This is my output :
[ { _id: 0, value: 2 },
{ _id: 1, value: 4 },
{ _id: 2, value: 2 } ]
I try to do this:
....
o.map = function () {
emit(this.id, {
startDate: this.startDate
})
}
....
model.find({
startDate: {
"$gte": new Date()
}
}).exec(function (err, docs) {
console.log(docs);
});
....
but I keep getting the same output.
So how do I add more key-value params from the map function to the result dictionary of the reduce function?
This is a solution :
var o = {};
o.map = function () {
emit(this.id, {
startDate: this.startDate,
cure: this.cure,
test: 'test'
// list other fields like above to select them
})
}
o.reduce = function (k, vals) {
return {
n: vals.length,
startDate: vals[0].startDate,
cure: vals[0].cure,
test: vals[0].test
}
}
o.out = {
replace: 'createdCollectionNameForResults'
};
o.verbose = true;
Session.mapReduce(o, function (err, model, stats) {
console.log('map reduce took %d ms', stats.processtime);
model.find({
'value.cure':mongoose.Types.ObjectId('52aedc805871871a32000004'),
'value.startDate': {
"$gte": new Date()
}
}).exec(function (err, docs) {
if(!err)
console.log(docs.length);
});
});

Categories

Resources