i'm new to meteor framework
I want to fetch single from the collection
AccountNames = new Mongo.Collection("AccountTypeMaster");
I created a collection using
db.createCollection("AccountTypeMaster")
this.helpers({
AccountNames: () => {
return AccountNames.find({}, {fields: {name: 1}});
}
});
Using above query i'm unable to fetch single field "name" from collection.
I'm now sure what's wrong with my code.
You need to change how you instantiate your collection. The correct Meteor syntax would be:
AccountNames = new Mongo.Collection("AccountTypeMaster");
Helpers also need to be attached to a template. Remember, helpers only run on client-side code.
if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
tasks: function () {
return AccountNames.find({}, { fields: { name: 1 } });
}
});
}
Create Client folder in your project and put client side code into that folder.To create collection in mongodb
Template.name.helpers({
fun: function() {
return AccountNames.find({},{name: 1}).fetch();
})
Related
EDIT: Since I wasn't able to find a correct solution, I changed the
application's structure a bit and posted another question:
Mongoose - find documents not in a list
I have a MEAN app with three models: User, Task, and for keeping track of which task is assigned to which user I have UserTask, which looks like this:
const mongoose = require("mongoose");
const autopopulate = require("mongoose-autopopulate");
const UserTaskSchema = mongoose.Schema({
completed: { type: Boolean, default: false },
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
autopopulate: true
},
taskId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Task",
autopopulate: true
}
});
UserTaskSchema.plugin(autopopulate);
module.exports = mongoose.model("UserTask", UserTaskSchema);
In my frontend app I have AngularJS services and I already have functions for getting all users, all tasks, and tasks which are assigned to a particular user (by getting all UserTasks with given userId. For example:
// user-task.service.js
function getAllUserTasksForUser(userId) {
return $http
.get("http://localhost:3333/userTasks/byUserId/" + userId)
.then(function(response) {
return response.data;
});
}
// task-service.js
function getAllTasks() {
return $http.get("http://localhost:3333/tasks").then(function(response) {
return response.data;
});
}
Then I'm using this data in my controllers like this:
userTaskService
.getAllUserTasksForUser($routeParams.id)
.then(data => (vm.userTasks = data));
...and because of autopopulate plugin I have complete User and Task objects inside the UserTasks that I get. So far, so good.
Now I need to get all Tasks which are not assigned to a particular User. I guess I should first get all Tasks, then all UserTasks for a given userId, and then make some kind of difference, with some "where-not-in" kind of filter.
I'm still a newbie for all the MEAN components, I'm not familiar with all those then()s and promises and stuff... and I'm really not sure how to do this. I tried using multiple then()s but with no success. Can anyone give me a hint?
You can do at server/API side that will more efficient.
In client side, if you want to do then try below
var userid = $routeParams.id;
userTaskService
.getAllTasks()
.then((data) => {
vm.userTasks = data.filter(task => task.userId !== userid)
});
So I'm trying to fill a select component with a enum type from mongoose
In my user service the schema looks something like :
firstName: { type:String, required: true },
...
ris:{type: String, default: 'R', enum:['R', 'I', 'S']},
In my feathers service I can access the Model with "this.Model"
so in any hook I can do:
this.Model.schema.path('ris').enumValues); //['R','C','I']
and I get the values from the enum type.
Now since I can't create custom API methods other that the officials ones
Feathers calling custom API method
https://docs.feathersjs.com/clients/readme.html#caveats
https://docs.feathersjs.com/help/faq.html#can-i-expose-custom-service-methods
How can I create a service method/call/something so that I can call it in my
componentDidMount(){ var optns= this.props.getMyEnumsFromFeathers}
and have the enum ['R','C','I'] to setup my dropdown
I'm Using React/Redux/ReduxSaga-FeathersJS
I'd create a service for listing Enums in the find method:
class EnumService {
find(params) {
const { service, path } = params.query;
const values = this.app.service(service).Model.schema.path(path).enumValues;
return Promise.resolve(values);
}
setup(app) {
this.app = app;
}
}
app.use('/enums', new EnumService())
Then on the client you can do
app.service('enums').find({ query: {
service: 'myservice',
path: 'ris'
}
}).then(value => console.log('Got ', values));
I was trying to use this code, but, it does not work like plug and play.
after some play with the app service I figured out the code below
async find(params) {
const { service, path } = params.query;
const values = await this.app.service(service).Model.attributes[path].values;
return values || [];
}
setup(app) {
this.app = app;
}
I am not sure if it is a thing of what database is been used, in my case I am in development environment, so, I am using sqlite.
I have the following code:
import { Meteor } from 'meteor/meteor';
import { Items } from './collection';
if (Meteor.isServer) {
Meteor.publish('items', function(options, owner) {
let selector = {
$and: [{ ownerId: owner}]
}
return Items.find(selector, options);
});
}
And on the client side I have:
this.subscribe('items', () => [{
limit: this.getReactively('querylimit'),
sort: {dateTime: -1}
},
this.getReactively('ownerId')
]);
The above does not return any results. However, when I change the return statement to the following, it works!
return Items.find({ ownerId: '7QcWm55wGw69hpuy2' }, options); //works !!!
I'm not very familiar with Mongo/Meteor query selectors. Passing the query as a variable to Items.find() seems to be messing something up. Can someone please help me figure this out!
Thanks
You are trying to pass a function as the selector, which won't work. Functions can't be serialized and sent from the client to the server. Instead you need to evaluate the options and the owner separately. Here's an example:
var owner = this.getReactively('ownerId');
var options = {
limit: this.getReactively('querylimit'),
sort: {dateTime: -1}
};
this.subscribe('items', options, owner);
Note that the published documents will not arrive in sorted order, so unless you are using a limit, the sort doesn't help here.
Also note that if you need the subscription to rerun after the owner or query limit change, you'll need to subscribe inside of an autorun.
Here's a start on an improved implementation:
Meteor.publish('items', function(options, owner) {
// DANGER! Actually check this against something safe!
check(options, Object);
// DANGER! Should any user subscribe for any owner's items?
check(owner, Match.Maybe(String));
// Publish the current user's items by default.
if (!owner) {
owner = this.userId;
}
return Items.find({ ownerId: owner }, options);
});
How can I post an array of Schema.Types.ObjectId (s) to MongoDB? I'm trying to create User Groups, which is a group of the 'User' Model e.g.
var UserGroup = new Schema({
users: [{
type: Schema.Types.ObjectId,
ref: 'User'
}]
});
New UserGroup Function
module.exports.create = function(request, response) {
var group = new UserGroup({
users = request.body.users
});
group.save(function(error) {
if(error) { throw error; } else { response.send('Group Created Successfully.');
});
};
I'm currently using Postman to test the functionality, how exactly should the data be posted?
As a Javascript array i.e ['A_USER_ID', 'A_USER_ID'] ?
Thanks!
#Answer
I was using the older syntax of the select() function, and therefore was passing invalid parameters to the $push function. When sending the request, I simply pass the ObjectIds as id,id,id and once they get to the server, simply put it into an array using var my_array = request.body.users.split(','); and then push it to the database using the following:
$push: { users: { $each: my_array } }
I hope this was helpful, the documentation isn't particularly clear on this matter.
For creating a new model I need to pass just one attribute:
model.save({
name: 'bar'
});
Then the server will add extra attributes like the id for this model.
Actually the response of the server when I create the new model is
this request has no response data available.
What is the best way to get the extra attributes created by the server?
Should I fix the sever part?
Here's my code:
var ListView = Marionette.CompositeView.extend({
// some code
events: {
'click #create-user': 'createUser'
},
createUser: function (e) {
this.collection.create(this.newAttributes(e));
},
newAttributes: function (e) {
return {
name: $(e.currentTarget).val(),
};
}
appendHtml: function (collectionView, itemView) {
collectionView.$el.find('ul.list-users').append(itemView.el);
}
});
This question is not related to Marionette, which only extends views, not models.
Backbone will automatically incorporate any new attributes sent back from the server - there is nothing special that needs to be done on the client side. But for this to work, your server needs to return a JSON object of attribute-value pairs that you want to be set.