I am new at Mongoose/nodejs and I am struggling with a simple update of an array within an array.
Here's the schema:
var County = new Schema({
_id : Schema.ObjectId,
name : String,
biggestCity : String
});
var Country = new Schema({
_id : Schema.ObjectId,
name : String,
counties : {type: [County], ref: "County"}
});
var Continent = new Schema({
_id : Schema.ObjectId,
countries : {type: [Country], ref: "Country"},
});
And here's the update code I've been trying:
var continents = mongoose.model("Continent");
var update = { "countries.counties.name": newName, "countries.counties.biggestCity": newBiggestCity };
var conditions = { "_id": countryId, "countries.name": countryName, "countries.counties.name": countyName };
var options = { multi: false };
wagers.update(conditions, update, options, function(err, numAffected) {
//callback code...
});
When doing this, the error in err says "Can't append to array using string field name 'counties'". What does this mean? What am I doing wrong?
You should define the child object as another Schema, not just as a list of some anonymous object. (Reference.)
Try defining Country as a separate Schema, nest that in Continent, then do your update.
Related
I have a document model called school which in turn has two subdocuments:
students
class
Each student belongs to one class.
var classSchema = new Schema({
name: {type : String}
});
var studentSchema = new Schema({
name : {type : String, required:true},
class: { type: ObjectId, ref: 'Institute.classes' },
});
var schoolSchema = new Schema({
name : {type : String, required:true},
students : [studentSchema],
classes : [classSchema]
});
var School = mongoose.model('School', schoolSchema);
Now when I am fetching a student, I want to populate the class as well. I am doing this as:
var school_id = req.params.school_id;
var student_id = req.params.student_id;
School
.findOne({'_id': school_id, 'students._id': student_id})
.populate({path: 'students.class'})
.exec(function (err, data) {
done(err, data);
});
When I do this, I get following error:
"message": "Schema hasn't been registered for model \"School.classes\".\nUse mongoose.model(name, schema)",
"name": "MissingSchemaError"
Is is possible to populate a subdocument from another subdocument?
Any help is appreciated. Thanks :)
I succeed to make a deep population with find and the search key in first model, but now i want to find by key on the sub object generated by the deep populate.
I have three models : Product, Category, and Event
I want to find my Products by e_fk_club_id that is in Event model
I tried two solutions but they didn't work
First solution in find :
model.find({'categories.events.e_fk_club_id':id})`
Second solution with match :
`$match : { e_fk_club_id : id }`
these are my models
product.js
var ProductSchema = new mongoose.Schema({
p_id: Number,
p_name: String,
p_fk_category: {type: mongoose.Schema.Types.ObjectId, ref: 'categories'},
}
, {collection: 'products'});
module.exports = mongoose.model('products', ProductSchema);
Category.js
var CategorySchema = new mongoose.Schema({
c_id: Number,
c_name: String,
c_fk_event: {type: mongoose.Schema.Types.ObjectId, ref: 'events'},
}
, {collection: 'categories'});
module.exports = mongoose.model('categories', CategorySchema);
Event.js
var EventSchema = new mongoose.Schema({
e_id: Number,
e_name: String,
e_fk_club_id: Number,
}
, {collection: 'events'});
module.exports = mongoose.model('events', EventSchema);
This is the code which i am trying to fetch the data :
getProductsByClub:function (id, callback){
var model = require("Product");
//model
model .find({'categories.events.e_fk_club_id':id})
.populate({
path:'p_fk_category',
model:'categories',
populate:
{
path:'e_fk_event',
model:'events',
//$match : { e_fk_club_id : id }
}
})
.exec (function(err, doc){
if (err) {
callback(err) ;
} else {
callback(doc) ;
}
})
},
Is There any solution.
Thank you in advance.
First Schema:
const ProviderSchema = new mongoose.Schema({
provName : { type: String, index: true }
});
module.exports = mongoose.model('provider', ProviderSchema);
Second Schema:
const WebProviderSchema = new mongoose.Schema({
userId : { type: Schema.Types.ObjectId, ref: 'users'},
providerId : { type: Schema.Types.ObjectId, ref: 'providers'}
});
module.exports = mongoose.model('webProvider', WebProviderSchema);
How do I join these two schemas?
So far if I do the following, I only get data from the second schema:
webProvider
.find({userId : '23423df234434bc956'})
.populate("providers")
.exec( function (error, listData) {
console.log(listData);
});
To populate you should use local field providerId. Should be .populate("providerId") instead of .populate("providers").
webProvider.find({userId : '23423df234434bc956'})
.populate("providerId")
.exec( function (error, listData) {
console.log(listData);
});
To populate multiple field can use like :
.populate("providerId userId")
or
.populate("providerId")
.populate("userId")
I am facing an issue where mongoose query is not populating an array type.
Here is institute schema
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var InstituteSchema = new Schema({
name: String,
address: String,
city: String,
country: String,
zip: String,
owner: { type: mongoose.Schema.ObjectId, ref: 'User' },
teachers: [{type: mongoose.Schema.ObjectId, ref: 'Teacher'}],
categories: [String],
created : { type : Date, default : Date.now }
});
module.exports = mongoose.model('Institute', InstituteSchema);
And here is teacher Schema
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TeacherSchema = new Schema({
education: [{degree: String, instituteName: String}],
dob: Date,
photoUrl: String,
phoneNumber: String,
owner: {type: mongoose.Schema.ObjectId, ref: 'User'},
institutes: [{type: mongoose.Schema.ObjectId, ref: 'Institute'}],
subjects: [{type: mongoose.Schema.ObjectId, ref: 'Subject'}],
created : { type : Date, default : Date.now }
})
module.exports = mongoose.model('Teacher', TeacherSchema);
Here is a method which queries the institute by owner id
exports.mine = function (req, res, next) {
var ObjectId = mongoose.Types.ObjectId;
var userId = new ObjectId(req.user._id);
Institute.find({
owner: userId
}).populate('teachers').exec(function (err, institute) {
if (err) return next(err);
if (!institute) return res.json(401);
res.json(institute);
});
};
I can see from the db that institute has teacher added
db.institutes.find();
{
"_id" : ObjectId("554719a9f5be11c6d4369264"),
"owner" : ObjectId("5547199bf5be11c6d4369263"),
"country" : "USA",
"name" : "Raghvendra Singh",
"address" : "38589 Royal Ann Cmn",
"city" : "Fremont",
"zip" : "94536",
"created" : ISODate("2015-05-04T07:03:05.569Z"),
"categories" : [ "IIT", "Medical" ],
"teachers" : [ ObjectId("55471965f5be11c6d436925f") ],
"__v" : 3
}
But somehow the query method doesn't populate the teachers collection. The weird thing is that i don't even get the collection with object ids and it returns and institute with empty teacher array.
And when i remove the .populate('teachers') from the method call it indeed returns the teacher array with object ids.
I looked at the documentation and i can't see what am i doing wrong.
First you need to change your Model slightly as mention for teachers feild.
teachers: [ { teacher: { type: Schema.ObjectId, ref: "Teacher" } } ]
exports.mine = function (req, res, next) {
var ObjectId = mongoose.Types.ObjectId;
var userId = new ObjectId(req.user._id);
Institute.find({
owner: userId
}).populate('**teachers.teacher**').exec(function (err, institute) {
if (err) return next(err);
if (!institute) return res.json(401);
res.json(institute);
});
};
Then, change your populate parameter to teachers.teacher . It will work
Hello I have this problem when checking if a subdocument exist before pushing a new subdocument.
var UserSchema = new Schema({
name : String,
app_key : String,
app_secret : String,
tasks : [{type: Schema.ObjectId, ref: 'Task'}] // assuming you name your model Task
});
var TaskSchema = new Schema({
name : String,
lastPerformed : Date,
folder : String,
user : {type: Schema.ObjectId, ref: 'User'} // assuming you name your model User
});
With this, your query for all users, including arrays of their tasks might be:
User.findOne({...}).populate('tasks').run(function(err, user) {
var subdoc = user.tasks.id(mytask.id);
if(subdoc){
//not exist
//push
}
});
This is the error:
TypeError: Object has no method 'id'
You are getting that error because there is no 'id' field defined for the 'tasks' subdocument. You might have meant 'user.tasks._id', which will return the ObjectId that MongoDB adds to its documents by default.