When Im trying to execute a function and using mongoose to find values in collection I get error find() is not a function
I use require on my schema in the top of the component before the function
const resModel = require('../Backend/ResourcesModel')
const getResources = () => {
const cookie = document.cookie;
const token = cookie && cookie.split('=')[1];
const decode = JSON.parse(Buffer.from(token.split('.')[1], 'base64'));
const para = {UserId:decode.user_id};
console.log(para);
resModel.find(para)
.select('Food Marble Gold Solfour')
.then(result => console.log(result))
}
Model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ResourcesTemple = new Schema({
UserId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
Gold: {
type: String,
required: true
},
Solfour: {
type: String,
required: true
},
Marble: {
type: String,
required: true
},
Food: {
type: String,
required: true
}
}, {versionKey: false});
const Resources = mongoose.model('Resources', ResourcesTemple);
module.exports = Resources;
Error:
Uncaught TypeError: e.find is not a function
Related
I am trying to export my schema on a separate file to be used for setting virtuals:
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
toLowerCase: true
},
price: {
type: Number,
required: true,
min: 0
},
category: {
type: String,
enum: ['fruit', 'vegetable', 'dairy'],
toLowerCase: true
}
});
module.exports.Product = mongoose.model('Product', productSchema);
module.exports.productSchema = productSchema
and on a seperate file I want to create my instances using a virtual setter:
const mongoose = require('mongoose');
const { Product, productSchema } = require('./models/product');
mongoose.connect('mongodb://localhost:27017/farmStand', { useNewUrlParser: true })
.then(() => {
console.log('MONGO CONNECTION OPEN.')
}).catch(err => {
console.log('MONGO CONNECTION NOT OPEN!!!');
console.log(err);
});
productSchema.virtual('storeP').set(function (phrase) {
const input = phrase.split(' ');
console.log(input)
const name = input[0];
const price = parseInt(input[1]);
const category = input[2];
this.set({ name, price, category });
this.save();
});
let products = ['peach 1.99 fruit', 'strawberry 1.49 fruit', 'milk 1.99 dairy', 'honey 1.99 dairy', 'spinach 1.99 vegetable']
for (let product of products) {
const p = new Product({});
p.storeP = product
}
when I run the code there is no error but my data will not be stored on my database.
but if I copy my productSchema directly from the first file into the second one, it will be working fine! anything I missing when exporting?
I am trying to insert data into MongoDB database but I get this error Cannot read property 'push' of undefined.
I can't understand what is the issue is here in my code. please help me with the solution. I am a Student and learning it.
here I am trying to push service into the category Model. for that, I have created a one to many relations between service and category. but I can't push the services into the category.
Schema design for category & Service =======
const mongoose = require("mongoose")
const Schema = mongoose.Schema
const CategorySchema = new Schema({
name:{
type:String,
required:true
},
services:[
{
type:Schema.Types.ObjectId,
ref:'Service'
}
]
},{ timestamps:true })
const Category = mongoose.model("Cat", CategorySchema);
module.exports = Category;
service======
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const serviceSchema = new Schema({
title:{
type: 'String',
required: true
},
description:{
type: 'String',
required: true
},
image: {
type: 'String',
required: true
},
price: {
type: 'Number',
required: true
},
category: {
type:Schema.Types.ObjectId,
ref:'Cat'
}
})
const Service = mongoose.model("Service", serviceSchema);
module.exports = Service;
here is my service controller
postService:(req, res)=>{
const { title, price, description,category} = req.body;
const image = req.file.filename;
const service = new Service({
title,
price,
category,
description,
image,
});
service.save()
.then((service)=>{
const category = Category.findOneAndUpdate({_id: service.category})
category.services.push(service)
category.save()
console.log(category)
return res.redirect("/admin/services");
})
.catch((err) => {
console.log(err);
return res.redirect("/admin/services/create");
});
},
do like this:
postService: async(req, res)=>{
const { title, price, description,category} = req.body;
const image = req.file.filename;
const service = new Service({
title,
price,
category,
description,
image,
});
try {
await service.save()
let categoryModel = await Category.findById(category);//category should be an ObjectId
categoryModel.services.push(service)
await categoryModel.save()
return res.redirect("/admin/services");
} catch (err) {
console.log(err);
return res.redirect("/admin/services/create");
}
},
I am trying to update an Object, with new array data. I receive the message:
"MongooseError [CastError]: Cast to ObjectId failed for value "" at
path "playlistContent" "
And I receive "undefined".
When I console.log my array data, everything is fine, but I am not able to update my document, and I can't figure out why.
Here is my code:
router.post("/addspot/:id", async (req, res) => {
// Constants
let specficPlaylist = await Playlist.findById(req.params.id);
let spotFrequency = req.body.spotFrequency;
let spotAllocate = req.body.spotAllocate;
let populatedPlaylists = [];
await specficPlaylist.populate("playlistContent").execPopulate();
// For loop for passing in data in the right order
for (let i = 0; i < specficPlaylist.playlistContent.length; i++) {
if (i % spotFrequency == 0) {
populatedPlaylists =
populatedPlaylists + spotAllocate + ",";
}
populatedPlaylists =
populatedPlaylists +
specficPlaylist.playlistContent[i]._id+ ",";
}
// Array of data which I want to update my Object with
const playlistData = populatedPlaylists.split(",");
// Trying to update my specific document with the above data, but it fails
await Playlist.findOneAndUpdate(
{ _id: specficPlaylist._id},
{ playlistContent: playlistData },
{ new: true},
(err, docs) => {
}
);
res.redirect('back');
});
Can anybody help me out, how to pass the data the correct way, and then update my Playlist Object?
// My Schema:
const mongoose = require("mongoose");
const playlistSchema = new mongoose.Schema({
playlistName: {
type: String,
trim: true,
},
playlistDescription: {
type: String,
trim: true,
},
playlistUrl: {
type: String,
trim: true,
},
playlistContent: [{ type: mongoose.Schema.Types.ObjectId, ref: "Media" }],
playlistCreator: {
type: String,
trim: true,
},
});
mongoose.model("Playlist", playlistSchema);
I'm trying to run my test as follow using the TDD aproach. I have the same test running on another app (I copy paste it) and it works but in this test I get the following error:
TypeError: Attempted to wrap undefined property find as function
Model file
/*
Task Model Database models
*/
const mongoose = require('mongoose');
try {
module.exports = mongoose.model('Task');
} catch (error) {
const taskSchema = mongoose.Schema({
title: { type: String, required: true },
status: { type: Boolean, required: true }
});
module.exports = taskSchema;
}
/* Sample Test */
'use strict';
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const sinon = require('sinon');
const expect = chai.expect;
const Task = require('../../models/task');
chai.should();
chai.use(chaiAsPromised);
//TEST DRIVEN DEVELOPMENT
describe('Todo Controller', () => {
const expectedResult = { status: 201, tasks: [{}], message: '' };
//Testing if the array has a valid status
it('should get a valid status', done => {
const TodoMock = sinon.mock(Task);
TodoMock.expects('find').yields(null, expectedResult);
Task.find((err, result) => {
TodoMock.verify();
TodoMock.restore();
expect(result.status).to.be.equal(201);
done();
});
});
});
It looks like you have some scoping issues. I would write the model like this:
const mongoose = require('mongoose');
const taskSchema;
try {
taskSchema = mongoose.model('Task');
} catch (error) {
taskSchema = mongoose.Schema({
title: { type: String, required: true },
status: { type: Boolean, required: true }
});
}
module.exports = taskSchema;
I do not understand what the problem is.
And why each element from the 'tasks' array is null.
Schema = mongoose.Schema;
const userSchema = new Schema({
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
tasks: [{type: Schema.Types.ObjectId, ref: 'Task'}]
}
);
const taskSchema = new Schema({
title: String
});
const User = mongoose.model('User', userSchema);
const Task = mongoose.model('Task', taskSchema);
// Add some default to DB
const task1 = new Task({
title: "Welcome! Here You Can:"
});
const task2 = new Task({
title: "ADD EDIT DELETE SHARE your TASKS "
});
const defaultTasks = [task1, task2];
When create new User I Add defaultTasks
const newUser = {
email: req.body.email,
password: req.body.password,
tasks: defaultTasks
};
Get Users Tasks
app.get('/tasks/', function(req, res){
const email = req.query.user;
User
.findOne({email: email})
.populate('tasks')
.exec()
.then(foundUser => {
console.log(foundUser);
const data = [];
Object.keys(foundUser.tasks).forEach(function(key) {
const val = foundUser.tasks[key];
data.push([val.title, val._id]);
});
res.send(data);
console.log('Data to send ' + data);
});
});
Before .Populate() console.log {
{ tasks: [ 5cf78ac1d08ee617fc89f7ed, 5cf78ac1d08ee617fc89f7ee ]
After { { tasks: [],
Please Help! All that I found did not solve my problem.
Maybe problem in defaultTasks. But i dont see it.
Your code doesn't save your task to DB, it just creates an object. So later when you populate User there are no tasks in DB to be found.
const task1 = await new Task({
title: "Welcome! Here You Can:"
}).save();
// or
const task1 = await Task.create({
title: "Welcome! Here You Can:"
});
P.s. of course you can deal with asynchronous calls the way you want.