Hello for a project i need to log the export of .csv downloads.
I have searched a lot but still cannot find the answer.
I created a collection: 'tokens' in my mongoDB
The model is located in /src/models/token.coffee
the app is located in /src/app.coffee
controller located in /src/controllers/token.coffee
This is my model:
mongoose = require('mongoose')
timestamps = require('mongoose-timestamp')
enums = require './enums'
schema = mongoose.Schema
# Schema definition
TokenSchema = new schema
user:
type: mongoose.Schema.Types.ObjectId
ref: 'User'
required: true
first_name:
type: String
required: true
last_name:
type: String
required: true
status:
type: String
enums: enums.TokenStatuses.__values
default: enums.TokenStatuses.running
# Plugins
TokenSchema.plugin timestamps, createdAt: 'created_at', updatedAt: 'changed_at'
try
mongoose.model 'Token', TokenSchema
i call the following function from the controller:
create_tokens_record = (user_id) ->
User.findOne {_id: user_id}, (err, user) ->
obj =
user: user._id
first_name: user.first_name
last_name: user.last_name
token = new models.Token(obj)
console.log token
token.save (err) ->
return err if err
And the error is:
events.js:72
throw er; // Unhandled 'error' event
^
TypeError: undefined is not a function
at c:\Users\Daan\api\src\controllers\user.coffee:239:15
at Query.<anonymous> (c:\Users\Daan\api\src\node_modules\mongoose\lib\model.js:3435:16)
at c:\Users\Daan\api\src\node_modules\mongoose\node_modules\kareem\index.js:273:21
at c:\Users\Daan\api\src\node_modules\mongoose\node_modules\kareem\index.js:127:16
at process._tickDomainCallback (node.js:492:13)
I have no idea why my model is still undefined. Hope anyone can help me out!
I found the answer:
In my project there was a index.coffee where all the models were exported.
I forgot to add the newly created model to this file.
Related
I have mongoose schema with User data:
// user schema
const User = new Schema(
{
name: {type: String},
email: {type: String, unique: true},
// other fields
})
And User's daily statistics schema:
// Stats schema
const Stats = new Schema(
{
dateCreated: {type: Date, default: Date.now()},
stepsWalked: {type: Number, default: 0},
// other fields
userId: String // user id field
})
When i trying to generate multiple Stats schema objects with the same user id like this:
for (let i = 0; i < 40; ++i) {
statsData = await Stats.create({
userId: userData._id
})
}
I'm getting mongoose duplicate exception on second iteration of the loop.
Stack trace:
MongoError: E11000 duplicate key error collection: 5909aed3df9db12e2b71a579_.stats index: userId_1 dup key: { : "5991c027a572690bfd322c08" }
at Function.MongoError.create (node_modules/mongodb-core/lib/error.js:31:11)
at toError (node_modules/mongodb/lib/utils.js:139:22)
at node_modules/mongodb/lib/collection.js:669:23
at handleCallback (node_modules/mongodb/lib/utils.js:120:56)
at node_modules/mongodb/lib/bulk/unordered.js:465:9
at handleCallback (node_modules/mongodb/lib/utils.js:120:56)
at resultHandler (node_modules/mongodb/lib/bulk/unordered.js:413:5)
at node_modules/mongodb-core/lib/connection/pool.js:469:18
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
How can i implement one-to-many relationship with mongoose ?
I have huge amount of stats data for single user, so i can't store stats data as part of User schema like this:
// user schema
const User = new Schema(
{
name: {type: String, default: 'NaN'},
email: {type: String, unique: true, default: 'NaN'},
// other fields
stats: [Stats] // to many docs to store array in schema
})
I had a similar issue where I was getting duplicate key errors. What happened for me was in a subdocument, I had previously assigned a unique constraint on one field. After correcting that, I continued to get the error. So I could create one instance just fine, but would always get an error when creating a second instance.
The fix for me, which is what another commenter here has mentioned, is to drop that collection. After I dropped the collection, new document and subdocument creation worked just fine.
I got very strange problem here, I can save data through mongoose but cannot do the query.
Here is the code:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CategorySchema = new Schema({
store : {type: String, required: true, unique: true},
categories : [{
parent : String,
name : String,
}],
});
CategorySchema.index({store: 1, update_at: -1});
module.exports = mongoose.model('Category', CategorySchema);
When I try to do the query, I get this error:
(node:7412) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): ValidationError: CastError: Cast to
String failed for value "{ _id: 58dd019b1a06731b0990b878, store:
'Store-Name-Here', categories: [], __v: 0 }" at path "store"
I got very similar schema for other collections, they work fine but not this one.
This is how I do the query:
Category.findOne({store: 'Store-Name-Here'}).exec().then(result => console.log(result), err => console.log(err));
And
Category.find().exec(function(err, result) {
if (err)
return next(err);
console.log(result);
})
I think I found the problem. I tried to add a static method to category scheme named CategoryScheme.static.init(). After I removed that method, everything works fine. I think maybe there was already a method named init() for some reason, and I created one that may have overrode it. That's what caused the error.
I have a Users model structure somewhat like this:
const userSchema = new mongoose.Schema({
email: { type: String, unique: true },
password: String,
todosDo: [models.Do.schema],
}
And the child "Do" schema somewhat like this (in a different file):
const doSchema = new mongoose.Schema({
name: {type: String, default : ''},
user: {type: mongoose.Schema.ObjectId, ref: 'User'},
createdAt: {type : Date, default : Date.now}
});
And I'm trying to figure out how to retrieve the todosDo array for the signed in user. This is what I've got so far:
// Get all "Do" todos from DB
// Experimenting to find todos from certain user
User.findById(req.user.id, function(err, user){
if(err){
console.log(err);
} else {
doTodos = user.todosDo, // this obviously doesn't work, just an idea of what I was going for
console.log(doTodos);
finished();
}
});
Am I referencing the child/parent wrong or am I just not retrieving the array right? Any help is greatly appreciated!
As far I guess you may want to edit as raw js objects so you need to use lean() function. without using lean() function user is mongoose object so you can't modify it.
can try this one:
User.findById(req.user.id)
.lean()
.exec(function (err, user) {
if(err){
console.log(err);
return res.status(400).send({msg:'Error occurred'});
}
if(!user) {
return res.status(400).send({msg:'User Not found'});
}
doTodos = user.todosDo;
console.log(user.todosDo); // check original todos
console.log(doTodos);
return res.status(200).send({doTodos : doTodos }); // return doTodos
});
and to refer child schema in parent schema from different model you can access a Model's schema via its schema property.
say in doSchema.js file
const doSchema = new mongoose.Schema({
name: {type: String, default : ''},
user: {type: mongoose.Schema.ObjectId, ref: 'User'},
createdAt: {type : Date, default : Date.now}
});
module.exports = mongoose.model( 'DoSchema', doSchema );
in user.js file
var DoModel = require('./doSchema');// exact path
const userSchema = new mongoose.Schema({
email: { type: String, unique: true },
password: String,
todosDo: [DoModel.schema],
}
Thanks for your help everybody! My problem was that I needed to push all the newly created todos in the post route to todosDo, so then I could retrieve them at the get route. Everything's working now!
I'm having trouble trying to add instance methods to my schemas.
Here is an example:
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var schema = new mongoose.Schema ({
first_name: {type: String, required: true, trim: true},
last_name: {type: String, required: true, trim: true},
email: {type: String, required: true, unique: true, dropDups: true, trim:true},
hash: {type: String, required: true}
});
schema.methods = {
encrypt: function(pwd) {
if (!pwd) return '';
else return bcrypt.hashSync(pwd, bcrypt.genSaltSync(10));
},
test: function(logentry) {
console.log(this.email + ': ' + logentry);
}
};
mongoose.model('Users', schema);
And then in my code elsewhere I try to call one of the methods:
var mongoose = require('mongoose');
var Users = mongoose.model('Users');
function testFunction(email) {
Users.find({email:email}, function(error, user) {
user.test('Trying to make mongoose instance methods work.');
});
}
testFunction('goofy#goober.com');
And then I get the following error (stacktrace omitted):
user.test('Trying to make mongoose instance methods work.');
^
TypeError: undefined is not a function
I cannot for the life of me figure this out..
I am using mongoose 3.8. I know I'm doing something wrong, but I need another, much smarter and experienced pair of eyes to help me find it.
I've tried defining the methods like this too:
schema.methods.encrypt = function(pwd) {...};
schema.methods.test = function(logentry) {...};
But it doesn't seem to matter.
There was only one previous post like this that I could find on stack overflow and they resolved their error by making sure that their methods were defined before they called mongoose.model('name', schema). I've got them defined before, so I don't think it's the same problem. Any help would be much appreciated.
The problem is that Users.find gives you an array.
So, either:
Users.find({ email: email }, function (e, users) {
users[0].test('foo bar whatever');
});
or:
Users.findOne({ email: email }, function (e, user) {
user.test('foo bar whatever');
});
When I try this code in my Application:
app/models/Post.coffee
mongoose = require "mongoose"
CommentModel = require "./Comment"
Comment = CommentModel.Schema
Schema = mongoose.Schema
Post = new Schema {
title: String,
slug: {type: String, index: { unique: true, dropDubs: true }},
content: String,
author: String,
tags: [String],
comments: [Comment],
created: { type: Date, default: Date.now }
}
Post.statics.findBySlug = (slug, cb) ->
this.model("Post").findOne({ slug: slug }, cb)
PostModel = mongoose.model "Post", Post
module.exports = PostModel
app/models/Comment.coffee
mongoose = require("mongoose")
Schema = mongoose.Schema
Comment = new Schema {
author: String,
content: String,
approved: Boolean,
created: { type: Date, default: Date.now }
}
CommentModel = mongoose.model "Comment", Comment
module.exports = CommentModel
app/controllers/PostsController.coffee (Just one method)
commentDestroy: (req, res, next) ->
Post.findBySlug req.params.slug, (err, doc) ->
if (err)
return next err
if doc == null
res.send 404
return
doc.comments.id(req.params.comment).remove()
doc.save (err) ->
if err
next err
res.json doc
It ends with error:
TypeError: Object [object Object],[object Object],[object Object],[object Object],[object Object] has no method 'id'
at Promise.PostsController.commentDestroy (/home/r41ngoloss/Projects/www/my-express/app/controllers/PostsController.js:88:22)
at Promise.addBack (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/promise.js:128:8)
at Promise.EventEmitter.emit (events.js:96:17)
at Promise.emit (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/promise.js:66:38)
at Promise.complete (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/promise.js:77:20)
at Query.findOne (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/query.js:1533:15)
at model.Document.init (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/document.js:229:11)
at model.init (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/model.js:192:36)
at Query.findOne (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/query.js:1531:12)
at exports.tick (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/utils.js:408:16)
I already tried to find solution for my problem, but i found just this and I think, that I have schemas in right order (By require).
Thanks for every answer.
The reason that your are getting that error is that you are not getting the Comment schema correctly in the Post.coffee file. When I do what you did, the Comment variable is undefined. Modify the top of your Post.coffee file to:
mongoose = require "mongoose"
Comment = mongoose.model('Comment').schema
Schema = mongoose.Schema
Now the Comment variable is the schema of the Comment model.