Populate query in array nested documents - mongoose - node.js

My Output is in below image
and my populate query
Post.findOne({_id:req.query.id}).
populate('user').
populate('comment').
exec(function(err,docs){
if(err){
console.log(err);
}
console.log(docs);
res.send(docs);
});
});
How do I get user object data in comments array?

It used to be impossible with mongoose to populate fields of deeper populated objects directly in the query, but you could always use manual population by passing your resultdocs to the Comment.populate(comments, options, cb) method (http://mongoosejs.com/docs/api.html#model_Model.populate) inside your first callback.
With newer mongoose versions you should be able to do it directly using this syntax:
Post.
find().
populate({
path: 'comment',
populate: {
path: 'comments',
populate: 'user'
}
}
});

Related

Mongoose deleteMany using _id on nodejs

i have a ids of array ['123','456', '789']. i want delete all this array in mongodb
How i user it:
ScheduleModel.deleteOne({ _id: ['123','456', '789'] });
this is not working because this is not object Id
what i Need :
ScheduleModel.deleteOne({ _id: [ObjectId('123'), ObjectId('456'), ObjectId('789')] });
How to add object Id in array data. any how to resolve this issues. i need a solution on this.
It's not about ObjectId. you are using wrong syntax. You must use $in statement
ScheduleModel.deleteMany({ id: { $in: ['123','456','789'] } });
Use deleteMany with proper syntax.When there are many objectId at time Use $in.
Try this :
var deleteCondition = {
_id : {
//In Array you can pass your objectId
$in : ['123','456','789']
}
//You can pass other conditions
}
//deleteMany
ScheduleModel.deleteMany(deleteCondition, function (err, res) {
if (res) console.log(res)
})

How can I filter arrays in mongodb using mongoose?

I have created database with two collections. Each of these collections connected with relations.
Here I want to pass one item _id and check whether it passed to other collection as foreign key. If it's passed, I want to filter all items which consist as _id. How can I do that. Here my mongoose query and screenshot of db. Thank you
route.get("/:id",(req,res)=>{
Vehicles.find({
categories: [req.params.id]
}, (err, data)=>{
if(err){
console.log(err);
}else{
console.log(data);
}
});
PS: For an example I want to get all vehicles which have category id "60c58c2dcf82de0780051378" inside categories array.
Following the mongo document, you can query for all documents where categories is an array that contains the objectId req.params.id as one of its elements.
Vehicles.find({
categories: req.params.id,
}, (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
});

mongoose callback is not an array

In my models I have this
module.exports.getPhotosById = function(userId,callback){
Photos.findOne({userId:userId},callback);
}
Then in route I do
Photo.getPhotosById(req.user._id,function(err,result){
console.log(result);
console.log(result.length);
});
The first console output this
{ _id: 325657865435643245,
userId: '32443564',
photo: 'abc.jpg',
caption: 'abc'
}
but why it's not an array? because the second console's output is undefined.
result is a single document instead of an array because you're calling findOne, not find.
To get all of a user's photo docs, change your method to:
module.exports.getPhotosById = function(userId, callback){
Photos.find({userId: userId}, callback);
}
findone Returns one document(JSON) that satisfies the specified query criteria
find Returns the array of Objects.

Mongo / Express Query Nested _id from query string

Using: node/express/mongodb/mongoose
With the setup listed above, I have created my schema and model and can query as needed. What I'm wondering how to do though is, pass the express request.query object to Model.find() in mongoose to match and query the _id of a nested document. In this instance, the query may look something like:
http://domain.com/api/object._id=57902aeec07ffa2290f179fe
Where object is a nested object that exists elsewhere in the database. I can easily query other fields. _id is the only one giving an issue. It returns an empty array of matches.
Can this be done?
This is an example and not the ACTUAL schema but this gets the point across..
let Category = mongoose.Schema({
name: String
})
let Product = mongoose.Schema({
name: String,
description:String,
category:Category
})
// sample category..
{
_id:ObjectId("1234567890"),
name: 'Sample Category'
}
// sample product
{
_id:ObjectId("0987654321"),
name:'Sample Product',
description:'Sample Product Description',
category: {
_id:ObjectId("1234567890"),
name: 'Sample Category'
}
}
So, what I'm looking for is... if I have the following in express..
app.get('/products',function(req,res,next){
let query = req.query
ProductModel.find(query).exec(function(err,docs){
res.json(docs)
})
})
This would allow me to specify anything I want in the query parameters as a query. So I could..
http://domain.com/api/products?name=String
http://domain.com/api/products?description=String
http://domain.com/api/products?category.name=String
I can query by category.name like this, but I can't do:
http://domain.com/api/products?category._id=1234567890
This returns an empty array
Change your query to http://domain.com/api/object/57902aeec07ffa2290f179fe and try
app.get('/api/object/:_id', function(req, res) {
// req._id is Mongo Document Id
// change MyModel to your model name
MyModel.findOne( {'_id' : req._id }, function(err, doc){
// do smth with this document
console.log(doc);
});
});
or try this one
http://domain.com/api/object?id=57902aeec07ffa2290f179fe
app.get('/api/object', function(req, res) {
var id = req.param('id');
MyModel.findOne( {'_id' : id }, function(err, doc){
console.log(doc);
});
})
First of all increase your skills in getting URL and POST Parameters by this article.
Read official Express 4.x API Documentation
Never mind I feel ridiculous. It works just as I posted above.. after I fixed an error in my schema.

Waterline : Access populated value within a model

I am using sails.js to develop my first app. I have a waterline model as shown below.
//ModelA.js
module.exports = {
attributes: {
//more attributes
userId: {
model: 'user'
},
//more attributes
}
};
I am using the model in one of my controllers as shown below.
ModelA.find(options)
.populate('userId')
.exec(function (err, modelA) {
//some logic
//modelA.userId is undefined here
res.json(modelA); //userId is populated in the JSON output
});
How do I get access to the populated value inside the model?
ModelA.find returns array of items.
ModelA.find(options)
.populate('userId')
.exec(function (err, results) {
console.log(results[0].userId) //results is an array.
//res.json(modelA);
});
Or you can use ModelA.findOne for a single record
It's because find return an array of records. You have to use index to access an object and then userId of that object.
ModelA.find(options).populate('userId').exec(function (err, recordsOfModelA) {
if(err) console.log(err);
else console.log(recordsOfModelA[0].userId)
});

Resources