I am using mongoose for my mongodb.
I am trying to update the existing document with an array of data.
Here's my code:
exports.transactions = function(req,res)
{
var transactions = req.body.transactions;
transactions.forEach(function(transaction){
// console.log("hello "+transaction);
// });
console.log(req.body.user._id);
Dwolla.update({user_id: req.body.user._id}, {$push: {"transactions": {Amount: transaction.Amount, DestinationId: transaction.DestinationId, DestinationName: transaction.DestinationName, SourceId:transaction.SourceId,SourceName:transaction.SourceName,status:transaction.Status}}},
{ upsert: true},
function(err, model) {
if(err) console.log(err);
console.log("success");
}
);
});
}
The error i am getting when upsert is true is:
oldCb(error, result ? result.result : { ok: 0, n: 0, nModified: 0 });
TypeError: object is not a function
at Query.callback (E:\ndash-nodejs\node_modules\mongoose
)
at E:\ndash-nodejs\node_modules\kareem\index.js:177:19
at E:\ndash-nodejs\node_modules\kareem\index.js:109:16
at process._tickCallback (node.js:355:11)
Model:
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var dwollaSchema = new Schema({
user_id:{ type: String},
username: { type: String },
dwolla_id: { type: String },
transactions: [{
Amount: String,
DestinationId:String,
DestinationName:String,
SourceId:String,
SourceName:String,
status:String
}],
modified: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Dwolla',dwollaSchema);
Related
I have two schemas as below.
MirFile Schema
const mongoose = require("mongoose");
const {ObjectId} = mongoose.Schema
// Creating a Schema for uploaded files
const MirFileSchema = new mongoose.Schema({
createdAt: {
type: Date,
default: Date.now,
},
name: {
type: String,
required: [true, "Uploaded file must have a name"],
},
image:{
type:String
},
belongsTo:{
type:ObjectId,
ref:"MirFolder"
}
});
const File = mongoose.model("MirFile", MirFileSchema);
MirFileSchema.pre('remove', function(next) {
MirSubFile.remove({belongsTo: this._id}).exec();
next();
});
module.exports = File;
MirSubFileSchema
const mongoose = require("mongoose");
const {ObjectId} = mongoose.Schema
// Creating a Schema for uploaded subfiles
const MirSubFileSchema = new mongoose.Schema({
createdAt: {
type: Date,
default: Date.now,
},
text: {
type: String,
required: [true, "Uploaded file must have a text"],
},
image:{
type:String
},
belongsTo:{
type:ObjectId,
ref:"MirFile"
}
});
const File = mongoose.model("MirSubFile", MirSubFileSchema);
module.exports = File;
When I delete MirFile the document from MirSubFile which holds the _id of MirFile in belongsTo field must be deleted.I have used prehook but its not working.Any guide.?
Why don't you simply add your own 'deleteOne' or 'remove' Mongoose middleware on the MirFileSchema to deleteOne or remove all other documents
exports.DeleteMirFileSchema = (req, res) => {
MirFileSchema.deleteOne({ _id: req.query._id }, { new: true }, (err, data) => {
if (err) {
console.log(err);
let errorKeyArray = Object.keys(err.errors);
let msgArray = errorKeyArray.map((obj) => {
return err.errors[obj];
});
ResponseObj.errorResponse(res, { status: 400, msg: msgArray.join(", ") });
} else ResponseObj.successResponse(res, data);
});
};
I use Mongoose to MongoDb with Node.js/React/GraphQL.
I have a document Article who is related to another document Event who is related to several documents Tags. When I try to save my documents I always have a pending promise to into my tags in the Event document.
Result :
- Article is save related to Event
- Event is saved but not related to Tags
- Tags are saved but not related to Event
Expecting :
- Article is save related to Event
- Event is saved and related to Tags
- Tags are saved and related to Event
Two time, when my server was on the beginning is working without pending and error. So I think my problem is a time problem, but I don't know how to resolve it. I try to put some timeout but without success.
I have the following schema in Mongoose/MongoDb
//mode/event.js
'use strict';
//import dependency
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create new instance of the mongoose.schema. the schema takes an object that shows
//the shape of your database entries.
var EventSchema = new Schema({
createdAt: {
type: Date,
default: Date.now
},
name: {
type: String,
required: 'Kindly enter the name of the event'
},
description: String,
site_web: String,
themes: {
type: String,
enum: ['Economics', 'Politics', 'Bitcoins', 'Sports'],
default: 'Economics'
},
picture: String,
event_date_start: Date,
event_date_end: Date,
type_event: {
type: String,
enum: ['Confrontation','Standard'],
default: 'Standard'
},
teams: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Team'
}],
tags: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Tag'
}]
});
//export our module to use in server.js
module.exports = mongoose.model('Event', EventSchema);
//model/tag.js
'use strict';
//import dependency
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create new instance of the mongoose.schema. the schema takes an object that shows
//the shape of your database entries.
var TagSchema = new Schema({
name: {
type: String,
required: 'Kindly enter the name of the tag'
},
});
//export our module to use in server.js
module.exports = mongoose.model('Tag', TagSchema);
//model/article.js
'use strict';
//import dependency
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create new instance of the mongoose.schema. the schema takes an object that shows
//the shape of your database entries.
var ArticleSchema = new Schema({
// _id: String,
createdAt: {
type: Date,
default: Date.now
},
event: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Event',
required: 'Kindly enter the event'
},
body: String,
type: {
type: String,
enum: ['Confrontation','Standard'],
default: 'Standard'
},
url_source: String,
themes: {
type: String,
enum: ['Economics', 'Politics', 'Bitcoins', 'Sports'],
default: 'Economics'
},
type_media: {
type: String,
enum: ['video', 'web', 'podcast'],
default: 'web'
},
article_date: Date,
});
//export our module to use in server.js
module.exports = mongoose.model('Article', ArticleSchema);
In my schema Node.js/GraphQL I have the resolve function
createArticle: {
type: ArticleType,
args: {
event: {type: EventCreateType},
body: {type: GraphQLString},
type: {type: articleType},
url_source: {type: GraphQLString},
themes: {type: themesType},
//type_media: {type: new GraphQLList(mediaType)}
type_media: {type: mediaType},
article_date : {type: GraphQLString}
},
resolve: async (source, params) => {
if (params.event) {
var eventparams = params.event;
var tagparams = params.event.tags;
params.event.tags = null;
params.event = null;
var tagIds = [];
//traitement des tags
var inEvent = await EventsModel.findOne({'name':eventparams.name});
if(!inEvent){
inEvent = new EventsModel(eventparams);
if(tagparams){
if(tagparams.length !=0){
tagIds = await tagparams.map(async function(c) {
var inTag = await TagsModel.findOne(c);
if(!inTag){
inTag = new TagsModel(c);
inTag.save(function(err) {
if (err) {
console.log(err);
}});
}
return inTag;
});
console.log('******************************Le tableau**************************');
console.dir(tagIds);
console.log('********************************************************');
//inEvent.tags = tagIds;
Promise.all(tagIds).then(function(savedObjects) {
console.log('********************************************************');
console.log('Le Inside Tab:',savedObjects);
console.log('********************************************************');
// Do something to celebrate?
inEvent.tags = savedObjects;
}).catch(function(err) {
// one or both errored
console.log(err);
});
}
}
inEvent.save(function(err) {
if (err) {
console.log(err);
}});
}
console.log('*******************propriete inEvent*****************************');
console.dir(inEvent);
console.log('********************************************************');
var articleModel = new ArticlesModel(params);
articleModel.event = inEvent;
console.log('***********************propriete Article before save****************');
console.dir(articleModel);
console.log('********************************************************');
articleModel.save(function(err, article) {
if (err) {
console.log(err);
}
if (article) {
return ArticlesModel.findById(article._id)
.populate('article')
.populate('event')
.exec(function(error, articles) {
console.log('article saved: succes')
articles.article.articles.push(articles);
articles.article.save(function(err, article) {
if (err) {
console.log(err);
}
});
return articles;
})
}
});
return articleModel;
}
else{
console.log('verif 3');
}
console.log('verif 4');
}
},
I am trying to implement Auto increment in uisng mongoose.
But I am stuck.
Counter Schema
counter.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var counterSchema = new Schema({
_id: {type: String, required: true},
sequence_value: {type: Number, default: 1}
});
var Counter = module.exports = mongoose.model('Counter', counterSchema);
Product Schema
products.js
var productsSchema = new Schema({
productId: {type: String, require: false},
merchantId: {type: String, required: false}
)}
I have created counter collection and inserted one record inside it.
{
"_id" : "productId",
"sequence_value" : 1
}
Include method to increment the counter in the counter collection
//COUNTER COLLECTION
function getNextSequenceValue(sequenceName){
var sequenceDocument = Counters.findOneAndUpdate({
query:{_id: sequenceName },
update: {$inc:{sequence_value:1}},
new:true
});
return sequenceDocument.sequence_value;
}
Calling method to increment sequence number:
product.productId = getNextSequenceValue("productid");
But it's not working, nothing is getting saved in the products collection?
the next sequence should be
product.productId = getNextSequenceValue("productId"); // camelCase
in the counter collection you have added document with key productId (camelCase) but trying to get sequence with key productid (all lowercase)
mongo CLI
> function getNextSequenceValue(sequenceName){
...
... var sequenceDocument = db.counters.findOneAndUpdate(
... { "_id" : sequenceName },
... { $inc : { sequence_value : 1 } },
... { new : true }
... );
... return sequenceDocument.sequence_value;
... }
>
EDIT-2 with mongoose
var counterSchema = mongoose.Schema(
{
_id: { type: String, required: true },
sequence_value: { type: Number, default: 1 }
}
);
var Counters = mongoose.model('Counters', counterSchema);
var productsSchema = mongoose.Schema({
productId: {type: String, require: true},
merchantId: {type: String, required: false}
});
productsSchema.pre('save', function(next){
var doc = this;
Counters.findOneAndUpdate(
{ _id: 'productId' },
{ $inc : { sequence_value : 1 } },
{ new : true },
function(err, seq){
if(err) return next(err);
doc.productId = seq.sequence_value;
next();
}
);
}
);
var Product = mongoose.model('Product', productsSchema);
var testProduct = new Product({merchantId : 'test'})
testProduct.save(function (err, doc){
console.log('saved ' + doc )
})
output (with generated productId)
saravana#ubuntu:~/node-mongoose$ node app.js
`open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
Mongoose: counters.findAndModify({ _id: 'productId' }, [], { '$inc': { sequence_value: 1 } }, { new: true, upsert: false, remove: false, fields: {} })
Mongoose: products.insert({ productId: '36', merchantId: 'test', _id: ObjectId("5a5b27b860716d24007df611"), __v: 0 })
saved { __v: 0,
productId: '36',
merchantId: 'test',
_id: 5a5b27b860716d24007df611 }
^C
saravana#ubuntu:~/node-mongoose$
I am not a totally new populate user but now I do not know what's wrong.
Here I need to populate my designerId which is type of ObjectId. Take a look at my route.
ordersAdminRouter.route('/customorder/add')
.post(function(req, res){
body = req.body;
console.log(body);
CustomOrders.create(body, function(err, saved){
if (err) throw err;
Designs.findByIdAndUpdate(saved.designId, {$set: {status: 'Order Sent'}}, {new: true}).exec()
.then(function(updated){
return CustomOrders.findById(saved._id).populate(saved.designId).exec();
})
.then(function(orders){
res.json(orders);
})
.then(undefined, function(err){
console.log(err);
})
});
});
saved._id is working because when I remove the populate, it returns the document that I need without the populated document of course.
Take a look at my schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var customOrderSchema = new Schema({
designId: { type: Schema.Types.ObjectId, ref: 'customDesigns' },
size: { type: String },
quantity: { type: Number },
totalPrice: { type: Number },
paymentMode: { type: String },
rcpt_img: { type: String },
refNumber: { type: String }
});
module.exports = mongoose.model('customOrders', customOrderSchema);
Here is my customDesigns schema.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var customDesignSchema = new Schema({
item_name: { type: String },
price: { type: Number, default: 0 },
img_url_front: { type: String },
img_url_back: { type: String },
designer: { type: Schema.Types.ObjectId, ref: 'users' },
color: { type: String },
designDate: { type: Date, default: Date.now() },
status: { type: String, default: 'For Qoutation' }
});
module.exports = mongoose.model('customDesigns', customDesignSchema);
I need to admit that I am new to promises on mongoose & express and this is my first time doing so. But using populate, i use it more than I can think of. Any suggestions?
return CustomOrders.findById(saved._id).populate('designId').then(.. your code);
By the way, you dont must use .exec() then you want execute your query, .then executes query as well. You can skip .exec()
http://mongoosejs.com/docs/populate.html
http://mongoosejs.com/docs/api.html#query_Query-populate
I am use "mongoose": "^4.1.2". I have try to update a matchRate field when after a document being updated. But it doesn't work either not throw an any errors.
Here is code:
list.model.js
'use strict';
var mongoose = require('bluebird').promisifyAll(require('mongoose'));
import { Schema } from 'mongoose';
var ListSchema = new Schema({
name: { type: String, required: true },
user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
emails: [],
emailColRef: String,
matchCount: Number,
totalCount: Number,
matchRate: Number,
state: {
type: String,
enum: ['pending', 'complete', 'invalid']
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
default: {
type: Boolean,
default: false
}
});
ListSchema
.virtual('count')
.get(() => this.emails.length);
ListSchema
.post('update', function() {
// this.update({},{ $set: { matchRate: this.matchCount / this.totalCount } });//Not working
//////-------------OR---------------//////
// this.matchRate=this.matchCount / this.totalCount;//Not working
console.log(this.matchCount);//undefined
console.log(this.totalCount);//undefined
console.log(this.matchRate);//undefined
});
export default mongoose.model('List', ListSchema);
list.controller.js
.....
.....
.....
var newList = {};
newList.name = name;
newList.emails = emails;
newList.emailColRef = emailColRef;
newList.state = status;
newList.matchCount = matchCount;
newList.totalCount = totalCount;
var query = { name: req.body.name };
List.update(query, newList, function(err, doc) {
// index(req, res);
if (err) {
console.log("Error in list update ", err)
return;
}
fs.unlink(req.file.path, function(err) {
if (err) {
console.log("Error in removing file", err)
return;
}
});
console.log('Update list with match status');
});