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.
Related
I Set manually an uid to each item in my collections...I Want To Know It's Possible that I use uid for populate?
I Dont Want Use from '_id' because Have Many collections In My DB And should change many things...somthing like this :
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var PersonSchema = new Schema({
name : String
, age : Number
, stories : [{ type: String, ref: 'Story' }]
});
var StorySchema = new Schema({
_creator : { type: String, ref: 'Person' }
, title : String
, fans : [{ type: String, ref: 'Person' }]
});
var Story = mongoose.model('Story', StorySchema);
var Person = mongoose.model('Person', PersonSchema);
No, it is not possible to have a mongodb document without '_id' , if you want to avoid duplication of ids, you can put uid in '_id' before saving the document.
If you keep uid seperately, '_id' will get autopopulated as ObjectId.
Here is a clear example of how to do it (https://mongoosejs.com/docs/populate.html):
Story.
find(...).
populate({
path: 'fans',
select: 'name -_id' // <---------------'-_id' exclude _id field.
}).
exec();
I am creating a Node app that would need to check the fields of a collection and return what the data type is. For example if the field is "First Name" the data type would be "String". How would I get started creating a back end application that does this?
In case you are using mongoose , then Each field or nested field is addressed by path.
var myschema = new Schema({
...
name: {
first:{type: String, required: true,},
last :{type: String, required: true,},
...
});
here name.first and name.last are paths.
Now to know the type of name.last there is an Schema API, called path().So.
var pathmeta = myschema.path(name.last);
console.log(" datatype = "+pathmeta.instance);
console.log(" whole pathmeta structure is "+JSON.stringify(pathmetas));
should print this..
datatype = String
whole pathmeta structure is
{"enumValues":[],"regExp":null,"path":"text","instance":"String","validators":[],"setters":[],"getters":[],"options":{},"_index":null}
I have a user and doctor collection/model. here's the file it is in
module.exports = function(mongoose){
var User = mongoose.Schema({
username: {type : String, unique : true},
password : String,
nameOfOrg : String,
workers : [],
doctors : [{type : mongoose.Schema.Types.ObjectId, ref : Doctor}],
patients : [{type : mongoose.Schema.Types.ObjectId, ref : Patient}]
})
var Doctor = mongoose.Schema({
name : String,
address : String,
parentOrg :[{type : mongoose.Schema.Types.ObjectId, ref : User}],
patients :[{type : mongoose.Schema.Types.ObjectId, ref : Patient}]
})
var Patient = mongoose.Schema({
name : String,
DOS : String,
parentOrg :[{type : mongoose.Schema.Types.ObjectId, ref : User}],
parentDoctor : [{type : mongoose.Schema.Types.ObjectId, ref : User}]
})
var models = {
User : mongoose.model("user", User),
Doctor : mongoose.model("doctor", Doctor),
Patient : mongoose.model("patient", Patient)
};
return models;
}
I have a route handler like doctor/:name every time I go there I put the param in the db so doctor/doc1 adds doc1 to the name field in the doctors collection. Well every time that happens Im trying to add the objectId of this newly created document to the doctors array in the users collection. I think that is what you are supposed to do to use populate in the future to keep data separate in different collections then bring the appropriate parts together. Any ways I'm having problems adding the doctors ID to the doctors array in the users collection when I go to the route. here is the routing app.js code
mongoose.connect("mongodb://localhost/pop3");
var models = require("./db")(mongoose);
app.get("/:name", function(req, res){
var user1 = new models.User({"username": req.params.name})
user1.save(function(err, doc){
if(err){
console.log(err)
}
console.log(doc)
res.send(doc)
app.locals.user = doc
})
})
app.get("/doctor/:name", function(req, res){
var doctor = new models.Doctor({"name" : req.params.name, "parentOrg" : app.locals.user._id})
// app.locals.user.doctors.push(app.locals.user._id)
models.User.findOne({"username": app.locals.user.username}).push(doctor._id)
doctor.save(function(err, doc){
if(err){
console.log(err)
}
console.log(doc)
res.send(doc)
})
});
I tried to folow the mongoose doc on populate they show to do a similar thing I think by demoing this:
aaron.stories.push(story1);
aaron.save(callback);
I guess arron will be my user that was just saved.
stories will be the doctors field and
story1 will be the doctor.
I just couldn't do it
EDIT:: I get this error in the browser window:
TypeError: models.User.findOne(...).push is not a function
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]
}
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).