Mongoose Virtual Populate 4.5 One-to-Many - mongodb

I'm using the Mongoose 4.5 virtual populate API and am unable to get the virtual field to populate on the one side of a one-to-many.
const FilmSchema = new Schema({
title: String,
slug: String,
director: String
});
const DirectorSchema = new Schema({
name: String,
slug: String
});
DirectorSchema.virtual('films', {
ref: 'Film',
localField: 'slug',
foreignField: 'director'
});
const Film = mongoose.model('Film', FilmSchema, 'film');
const Director = mongoose.model('Director', DirectorSchema, 'director');
Director.find({}).populate('films').exec()
.then(data => res.send(data))
.catch(err => console.log(err));
The director data is output as expected but without any mention of films and without throwing/logging any errors.
In the query log, it looks like Mongoose is trying to do what I ask:
Mongoose: director.find({}) { fields: undefined }
Mongoose: film.find({ director: { '$in': [ 'spielberg', 'zemeckis', 'nolan' ] } }) { fields: undefined }
I've tried several variations, such as:
setting a ref to Director with type: String on FilmSchema.director
setting a ref to Director with type ObjectId on FilmSchema.director
replacing slug with a custom _id String
...and various combinations of the above.
I'm using the docs example and Valeri's recent article as guides.
Does anyone see what I'm doing wrong?
Versions: Node: 6.3.0 / MongoDB: 3.2.5 / Mongoose: 4.5.8

Answered by vkarpov15 on GitHub issues:
Try res.send(data.toObject({ virtuals: true })); or setting schema.options.toJSON = { virtuals: true }. Virtuals are not included by default when you transform a mongoose doc into a pojo

If you have set schema.options.toJSON = { virtuals: true } and are still not seeing your populated child objects, try explicitly calling .toJSON() - I was simply console.logging my objects and the data was not showing up! DOH!
ie:
const director = await Director.findOne({}).populate('films');
console.log(director);
>> { _id: 5a5f598923294f047ae2f66f, name: 'spielberg', __v: 0};
but:
const director = await Director.findOne({}).populate('films');
console.log(director.toJSON());
>> { _id: 5a5f598923294f047ae2f66f, name: 'spielberg', __v: 0,
films: [{_id: 5a5f598923294f047ae2f6bf, title:"ET"},{_id: 5a5f598923294f047ae2f30v, title:"Jaws"}]
};

Related

Create multiple documents from an array of values in Mongo DB

I'm new to MongoDB and I know this might sound silly to many but is there a way(s) where you can create multiple documents from an array of values. I have written some code for this, but is there any other efficient/shorter way of doing that.
tags.map(async tag => {
const tagDoc = await TagModel.create({ tag, postID })
})
Tag Schema -
const tagSchema = new mongoose.Schema({
postID: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Post",
}],
tag: {
type: String,
required: true,
},
}, { timestamps: true })
Case 1 : Storing Tags in Same Collection
in mysql you have to store tags in different table , but in mongodb you can use same collection to store tags as array of string
in your post schema :
const postSchema = new mongoose.Schema({
...
tags: {
type: [String],
required: true,
}
});
when saving post =>
let post = new Post();
...
post.tags = req.body.tags; // ["Tag1","hello","Testing"];
await post.save();
Case 2 : Storing Tags in Different Collection
if you want to store tags in different collection Tag , then you can use Mongoose InsertMany()
let tags = req.body.tags ; // ["Tag1","hello","Testing"];
tagsArray = tags.map((t)=> { return {postID:post._id , tag:t}});
let tagsSaved = await Tag.insertMany(tagsArray);
console.log('tagsSaved=',tagsSaved);

Why can't mongo push my ObjectId in a predefined array?

I have made my model, it has this Schema:
const CompanySchema = new Schema({
companyName: {
type: String,
required: [true,'the name of the companies working on the game are missing.']
},
companyAge: {
type: Number,
required: [true,'the age of the company is missing.']
},
companyDeveloper:[{
type: Schema.Types.ObjectId,
ref: "developer"
}]
});
I am trying to push a element into the companyDeveloper array like this:
addDev(req,res,next){
const companyId = req.params.id;
const companyDeveloper = ObjectId.fromString(req.body.companyDeveloper);
Company.findById({_id: companyId})
.then((company) => company.companyDeveloper.push({companyDeveloper}))
.then(company => res.send(company))
.catch(next);
}
but I keep getting this error:
"error": "ObjectId is not defined".
Before I tried casting it, I got this error
Cast to ObjectId failed for value
How can I get this function to work?
printscreen
postman call error
The ObjectId class from mongoose is defined on Mongoose.Schema.Types.ObjectId
You can require it in the file where you define addDev
const ObjectId = require('mongoose').Schema.Types.ObjectId
or load mongoose into a global where you initialize your node code so you can access it in any file:
global.Mongoose = require('mongoose')
And then use it in your method:
const companyDeveloper = Mongoose.Schema.Types.ObjectId.fromString(req.body.companyDeveloper);

Mongoose populate() returning empty array

so I've been at it for like 4 hours, read the documentation several times, and still couldn't figure out my problem. I'm trying to do a simple populate() to my model.
I have a User model and Store model. The User has a favoriteStores array which contains the _id of stores. What I'm looking for is that this array will be populated with the Store details.
user.model
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var UserSchema = new Schema({
username: String,
name: {first: String, last: String},
favoriteStores: [{type: Schema.Types.ObjectId, ref: 'Store'}],
modifiedOn: {type: Date, default: Date.now},
createdOn: Date,
lastLogin: Date
});
UserSchema.statics.getFavoriteStores = function (userId, callback) {
this
.findById(userId)
.populate('favoriteStores')
.exec(function (err, stores) {
callback(err, stores);
});
}
And another file:
store.model
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var StoreSchema = new Schema({
name: String,
route: String,
tagline: String,
logo: String
});
module.exports = mongoose.model('Store', StoreSchema);
After running this what I get is:
{
"_id": "556dc40b44f14c0c252c5604",
"username": "adiv.rulez",
"__v": 0,
"modifiedOn": "2015-06-02T14:56:11.074Z",
"favoriteStores": [],
"name": {
"first": "Adiv",
"last": "Ohayon"
}
}
The favoriteStores is empty, even though when I just do a get of the stores without the populate it does display the _id of the store.
Any help is greatly appreciated! Thanks ;)
UPDATE
After using the deepPopulate plugin it magically fixed it. I guess the problem was with the nesting of the userSchema. Still not sure what the problem was exactly, but at least it's fixed.
I think this issue happens when schemas are defined across multiple files. To solve this, try call populate this way:
.populate({path: 'favoriteStores', model: 'Store'})

mongo mongoose populate subdocument returns null

I am trying to use node & mongoose's populate method to kind of 'join' 2 collections on query. The following is my schema setup:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ShopSchema = new Schema({
ssss: { type: Schema.Types.ObjectId, required :true, ref: 'Stat' },
ratings: [RatingSchema]
});
var RatingSchema = new Schema({
stat: { type: Schema.Types.ObjectId, required :true, ref: 'Stat' }
}, {_id: false});
Also I have setup the Stat mongoose model so that the queries works without error (but the result is not what I expected).
I tried to perform the following queries:
ShopSchema.statics.load = function(id, cb) {
this.findOne({
_id: id
}).populate('ssss', '_id stat_id').exec(cb);
};
mongoose.model('Shop', ShopSchema);
This gives me the correct result and the ssss is correctly referenced.
The result is something like this .
"ssss":{"_id":"5406839ad5c5d9c5d47091f0","stat_id":1}
However, the following query gives me the wrong result.
ShopSchema.statics.load = function(id, cb) {
this.findOne({
_id: id
}).populate('ratings.stat', '_id stat_id').exec(cb);
};
mongoose.model('Shop', ShopSchema);
This gives me ratings.stat = null for all results. Could someone tell me what I did wrong? Thanks.
I just found the answer by trial and error.....
in the last example ShopSchema is declared before the RatingSchema. So I am guessing Mongoose doesn't know exactly what is happening inside RatingSchema and making the populate returns an error. So if you declare RatingSchema before the ShopSchema and the populate method is working like a charm..

Mongoose: Populate a populated field

I'm using MongoDB as a log keeper for my app to then sync mobile clients. I have this models set up in NodeJS:
var UserArticle = new Schema({
date: { type: Number, default: Math.round((new Date()).getTime() / 1000) }, //Timestamp!
user: [{type: Schema.ObjectId, ref: "User"}],
article: [{type: Schema.ObjectId, ref: "Article"}],
place: Number,
read: Number,
starred: Number,
source: String
});
mongoose.model("UserArticle",UserArticle);
var Log = new Schema({
user: [{type: Schema.ObjectId, ref: "User"}],
action: Number, // O => Insert, 1 => Update, 2 => Delete
uarticle: [{type: Schema.ObjectId, ref: "UserArticle"}],
timestamp: { type: Number, default: Math.round((new Date()).getTime() / 1000) }
});
mongoose.model("Log",Log);
When I want to retrive the log I use the follwing code:
var log = mongoose.model('Log');
log
.where("user", req.session.user)
.desc("timestamp")
.populate("uarticle")
.populate("uarticle.article")
.run(function (err, articles) {
if (err) {
console.log(err);
res.send(500);
return;
}
res.json(articles);
As you can see, I want mongoose to populate the "uarticle" field from the Log collection and, then, I want to populate the "article" field of the UserArticle ("uarticle").
But, using this code, Mongoose only populates "uarticle" using the UserArticle Model, but not the article field inside of uarticle.
Is it possible to accomplish it using Mongoose and populate() or I should do something else?
Thank you,
From what I've checked in the documentation and from what I hear from you, this cannot be achieved, but you can populate the "uarticle.article" documents yourself in the callback function.
However I want to point out another aspect which I consider more important. You have documents in collection A which reference collection B, and in collection B's documents you have another reference to documents in collection C.
You are either doing this wrong (I'm referring to the database structure), or you should be using a relational database such as MySQL here. MongoDB's power relies in the fact you can embed more information in documents, thus having to make lesser queries (having your data in a single collection). While referencing something is ok, having a reference and then another reference doesn't seem like you're taking the full advantage of MongoDB here.
Perhaps you would like to share your situation and the database structure so we could help you out more.
You can use the mongoose-deep-populate plugin to do this. Usage:
User.find({}, function (err, users) {
User.deepPopulate(users, 'uarticle.article', function (err, users) {
// now each user document includes uarticle and each uarticle includes article
})
})
Disclaimer: I'm the author of the plugin.
I faced the same problem,but after hours of efforts i find the solution.It can be without using any external plugin:)
applicantListToExport: function (query, callback) {
this
.find(query).select({'advtId': 0})
.populate({
path: 'influId',
model: 'influencer',
select: { '_id': 1,'user':1},
populate: {
path: 'userid',
model: 'User'
}
})
.populate('campaignId',{'campaignTitle':1})
.exec(callback);
}
Mongoose v5.5.5 seems to allow populate on a populated document.
You can even provide an array of multiple fields to populate on the populated document
var batch = await mstsBatchModel.findOne({_id: req.body.batchId})
.populate({path: 'loggedInUser', select: 'fname lname', model: 'userModel'})
.populate({path: 'invoiceIdArray', model: 'invoiceModel',
populate: [
{path: 'updatedBy', select: 'fname lname', model: 'userModel'},
{path: 'createdBy', select: 'fname lname', model: 'userModel'},
{path: 'aircraftId', select: 'tailNum', model: 'aircraftModel'}
]});
how about something like:
populate_deep = function(type, instance, complete, seen)
{
if (!seen)
seen = {};
if (seen[instance._id])
{
complete();
return;
}
seen[instance._id] = true;
// use meta util to get all "references" from the schema
var refs = meta.get_references(meta.schema(type));
if (!refs)
{
complete();
return;
}
var opts = [];
for (var i=0; i<refs.length; i++)
opts.push({path: refs[i].name, model: refs[i].ref});
mongoose.model(type).populate(instance, opts, function(err,o){
utils.forEach(refs, function (ref, next) {
if (ref.is_array)
utils.forEach(o[ref.name], function (v, lnext) {
populate_deep(ref.ref_type, v, lnext, seen);
}, next);
else
populate_deep(ref.ref_type, o[ref.name], next, seen);
}, complete);
});
}
meta utils is rough... want the src?
or you can simply pass an obj to the populate as:
const myFilterObj = {};
const populateObj = {
path: "parentFileds",
populate: {
path: "childFileds",
select: "childFiledsToSelect"
},
select: "parentFiledsToSelect"
};
Model.find(myFilterObj)
.populate(populateObj).exec((err, data) => console.log(data) );