Node Js MongoDB add multiple datalines - javascript

Hi need some help using Node Js to add data to MongoDB.
My route looks like this
app.get('/article/:id/add', function(req, res) {
Listing.findOne(req.params.id, function (err, p) {
if (err) throw err;
res.render('', {});
});
});
my Schema like this
article: {
ownerid : String,
name : String,
imagename : String,
interessted_user : {
id : String
}
}
If a User Hit the "Add" button at the frond end, Ajax execute get /article/:id/add.
How can Add multiple Users who are interested in this article to MongoDB.
It should look something like this.
article: {
ownerid : String,
name : String,
imagename : String,
interessted_user : {
id : 123456789098765432123456789,
765432123456765432345676543,
234567654321345678765432234
}
}
So later on i want to show the owner of this article all the interested users.

You could use an array, so the schema becomes:
{
article: {
ownerid : String,
name : String,
imagename : String,
interessted_user : Array
}
}
Then a row should look like this:
article: {
ownerid : String,
name : String,
imagename : String,
interessted_user : [123456789098765432123456789, 765432123456765432345676543, 234567654321345678765432234]
}

Related

Validating user using .pre save

My API accepts users POSTed as JSON. I would like to validate certain fields only if they are included as part of the JSON object.
For example, a user might look like this:
{
"email" : "test#test.com",
"username" : "testing",
"name" : "Test User"
}
or it might not have a name field:
{
"email" : "test#test.com",
"username" : "testing"
}
and I would like to make sure name has at least 6 characters if it is an included field.
I'm trying to build the validation process into my model using .pre but things aren't quite as I'd expect them.
var UserSchema = new Schema({
id : String,
name : String,
email : String,
username : String
},{ timestamps: { createdAt: 'created_at',updatedAt: 'updated_at' } });
UserSchema.pre('save', function(next) {
console.log(this); //no evidence of name property here
if("name" in this){
console.log("Name found"); //this is always the output
} else {
console.log("Name not found");
}
next();
});
The above code is for testing. Using either of the JSON objects above, the output is always "Name found" even though the object doesn't have a name property when I output to the console. Is this because the model has a name property?
You see the user object in the terminal and there is no property for name because the posted json might not have a name field as you mentioned, so you may do your logic/condition just when the name property is existed as follow:
UserSchema.pre('save', function(next) {
if (this.name !== undefined) {
if (this.name.length <= 6) {
// throw error or whatever
}
}
next();
});

Subscribe to a child array of the collection document

I have a collection which represents the uploaded files for the user with a structure like so:
{
_id : SKHdspjhs92346
files : [ { file_name : "1.txt" , file_path : "/home/test1"/} , { file_name : "2.txt" , file_path : "/home/test2"/} ]
}
I want to subscribe to this collection array changings.
So when client uploads a file im doing a push :
AttachmentsList.update({_id : id},
{ $push: { files : {file_name : fileName, file_path: filePath}}});
And a pull when deleted:
AttachmentsList.update( {"_id": id }, {"$pull": { "files" : {file_name : fileName,file_path: filePath} } } );
I want the elements dinamically change in template. Is it possible to do so? Currently i have this publisher
Meteor.publish("attachments_list_limited", function (count,id) {
var test = AttachmentsList.find({_id : id}, { "files.$": 1 },{limit: count}, {sort: {"files.file_name": -1}});
console.log("changed, gout elements: " + test.count());
return test;
});
But it doesnt work reactively like that.
You could have a look at https://github.com/peerlibrary/meteor-reactive-publish to try to make your publish reactive to the user structure's updates through #autorun.

Node.js find document by an element in array

I have a user schema with the following structure:
new Schema({
email : String,
password : String,
shoppingCart : [{type : Schema.Types.ObjectId, ref : 'Product'}]
});
and I also have a product schema as follows:
new Schema({
title : String,
description : String,
vendorId : String,
stock : Number
});
How could I search for the users which have a specific product within their shopping carts?
I tried both
UserModel.find({shoppingCart : product._id})...
and
UserModel.find({'shoppingCart._id' : product._id})....
but unfortunately it does not work. Any ideas? Thanks.
Have you tried...
UserModel.find({shoppingCart : product})
If you use the actual object within the query, it will hydrate itself into ID and runs the search based on that object ID.
Since you have a Schema type as "Schema.Types.ObjectId" if you run
UserModel.find({shoppingCart : product._id})
It will search against product._id as "String" not ObjectId.

mongoose query for top 5 viewed projects (sorted) using nodeJS

i have a site with multiple projects. and each project has a different view count.
What i want to do is to retrieve an array of the top 5 viewed projects in this order [max, max-1, max-2, max-3, max-4].
here's the schema:
var mongoose = require('mongoose');
// defines the database schema for this object
var schema = mongoose.Schema({
projectName : String,
authorName : String,
viewCount : Number
comment : [{
id : String,
authorName : String,
authorEmailAddress : { type : String, index : true }
}]
});
})
// Sets the schema for model
var ProjectModel = mongoose.model('Project', schema);
// Create a project
exports.create = function (projectJSON) {
var project = new ProjectModel({
projectName : projectJSON.projectName ,
authorName : projectJSON.authorName,
viewCount : projectJSON.viewCount,
comment : [{
id : projectJSON.comments.id,
authorName : projectJSON.comments.authorName,
authorEmailAddress : projectJSON.authorEmailAddress
});
project.save(function(err) {
if (err) {
console.log(err);
}
else{
console.log("success");
}
});
}
Below is my attempt to retrieve an array of the top 5 viewed articles in this order [max, max-1, max-2, max-3, max-4]. Bearing in mind that articles view rank change in real time.
// because i am familiar with SQL, i start with a SQL query and convert it later to mongoose
SQL version:
SELECT MAX(viewCount) FROM project where projectName=1 --this only give the MAX when i want the top 5
mongoose version:
exports.getTopViewedProject = function(rank, callback)
ProjectModel.findOne({ projectName: 1 }).sort(viewCount, -1).run(
function(err, viewCOunt) {
var max = viewCount;
});
To get the top 5 articles for project 'name' by viewCount:
ProjectModel.find({projectName: 'name'}).sort({viewCount: -1}).limit(5).exec(
function(err, projects) {
...
}
);

MongooseJS schema relation

I have MongooseJS schema as follow:
var UserSchema = new Schema({
name : String,
app_key : String,
app_secret : String,
tasks : [{ type : Schema.ObjectId,
ref : 'Task'}]
})
var ActionSchema = new Schema({
name : String,
description : String,
module : String
})
var enumTaskState = ['New', 'Indexing', 'Idle', 'In Queue', 'Working'];
var TaskSchema = new Schema({
name : String,
lastPerformed : Date,
folder : String,
actions : [{type : Schema.ObjectId,
ref : 'Task'}],
user : { type : Schema.ObjectId,
ref : 'User'},
status : { type : String,
enum : enumTaskState,
default : 'New'}
})
Problem is, when I set a task's user, do I manually have to go to the user and add a task there too? This seems like extra work (redundancy), is there an option in mongoosejs that will allow me to specify the relations it will handle everything by itself?
Thanks.
MongoDB is not a relational database, it is a document based based database.
You can get a user's list of tasks by querying the TaskSchema and looking for the user you want. Just make sure to add an index so it will be a fast query:
user: {type: Schema.ObjectId, ref: 'User', index: true}
To elaborate on emostar's answer:
You're trying to use MongoDB like a relational database. You're giving Users a list of Tasks, but each Task is referencing a User. In a typical MongoDB schema, you'd figure out how you want to use the models in your app and just embed the documents where it makes sense (e.g. if Users contains an array of Tasks, there's no need for a task to have a reference to it's owner--just look at the User that owns the collection).

Categories