Populating in array of object ids - node.js

My schema:-
var playlistSchema = new Schema({
name : {type:String,require:true},
videos : {type:[mongoose.Schema.Types.ObjectId],ref: 'Video'},
},{collection:'playlist'})
var Playlist = mongoose.model('Playlist',playlistSchema);
I have some data in the database as exapmple:-
{
"_id" : ObjectId("58d373ce66fe2d0898e724fc"),
"name" : "playlist1",
"videos" : [
ObjectId("58d2189762a1b8117401e3e2"),
ObjectId("58d217e491089a1164a2441f"),
ObjectId("58d2191062a1b8117401e3e4"),
ObjectId("58d217e491089a1164a24421")
],
"__v" : 0
}
And the schema of Video is :-
var videoSchema = new Schema({
name : {type:String,required:true},
createdAt : {type:String,default:new Date()},
isDisabled : {type:Boolean,default:false},
album : {type: mongoose.Schema.Types.ObjectId, ref: 'Album'}
},{collection:'video'})
var Video = mongoose.model('Video',videoSchema);
Now in order to get the name of the all the videos in playlist i am trying the code:-
var playlistModel = mongoose.model('Playlist');
let searchParam = {};
searchParam._id = req.params.pid;
playlistModel.findOne(searchParam)
.populate('[videos]')
.exec(function(err,found){
if(err)
throw err;
else{
console.log(found.videos[0].name);
}
})
But here i am getting the undefined result.I am not getting where i am wrong plzz anyone help me to short out this problem.

got the answer:-
just change the schema
var playlistSchema = new Schema({
name : {type:String,require:true},
videos : [{type:mongoose.Schema.Types.ObjectId,ref: 'Video'}],
},{collection:'playlist'})
var Playlist = mongoose.model('Playlist',playlistSchema);
and just use
.populate('videos')
instead of
.populate('[videos]')

const app = await this.appModel.findOne({ slug })
.populate({
path: 'category',
populate: {
path: 'subCategories',
model: 'Category',
select: { name: 1, slug: 1, _id: 0 }
},
});

Related

Response output not showing entire information present in mongoose schema nodejs

I have designed a Mongoose schema like this :
const metricsSchema = mongoose.Schema({
_id : mongoose.Schema.Types.ObjectId,
level : String,
details: {
demo: String,
full: String
}
});
Also, I have handled the response as such :
router.post('/',(req, res, next)=>{
const metrics = new Metrics({
_id : new mongoose.Types.ObjectId(),
level : req.body.level,
details:{
demo: req.body.demo,
full: req.body.full
}
});
res.status(201).json({
metrics: metrics
})
});
However, when I use Postman to post JSON data like this :
{
"level" :"schema" ,
"details":{
"demo" : "2465",
"full" : "1211234"
}
}
I get output like this :
{
"metrics": {
"_id": "5e09c156b0ce8a4a54a3ecca",
"level": "schema"
}
}
I do not get the rest of the output : demo and full in the response json. I wish to get the output like this :
{
"metrics": {
"_id": "5e09c156b0ce8a4a54a3ecca",
"level": "schema"
"details": {
"demo": "2465",
"full": "1211234"
}
}
}
Update: I found one solution in which the Mongoose schema was divided into two parts :
const detailsSchema = mongoose.Schema({
_id : mongoose.Schema.Types.ObjectId,
demo: String,
full: String
});
mongoose.model('Details',detailsSchema );
const metricsSchema = mongoose.Schema({
_id : mongoose.Schema.Types.ObjectId,
level : String,
details: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Details'
}
});
However, this did not work as well.
You have to change the code as below:
router.post('/',(req, res, next)=>{
const metrics = new Metrics({
_id : new mongoose.Types.ObjectId(),
level : req.body.level,
details:{
demo: req.body.details.demo, <----- see the change here
full: req.body.details.full
}
});
res.status(201).json({
metrics: metrics
})
});

Pushing items to a nested array from an express post request

Below is the schema for my monthly budgets collection. Each of them is assigned a year and a month. Each budget has a multiple categories and sub-categories within each of them. I have decided to store them in an array.
var {mongoose} = require('../db/mongoose');
var mb = new mongoose.Schema({
month: String,
categories: [{
name: String,
sub_categories: [{
name: String,
amount: Number
}]
}]
});
var Monthly_Budgets = mongoose.model('Monthly_Budgets', mb);
module.exports = {
Monthly_Budgets
};
Below is the post express post request
app.post('/monthlyBudgets', (req, res) => {
var sub_categories = req.body.categories.sub_categories;
var categories = [{
name : req.body.categories.name,
sub_categories
}]
var budgets = new Monthly_Budgets({
month : req.body.month,
year: req.body.year
})
budgets.categories = categories;
budgets.save().then((docs) => {
res.send(docs);
console.log(docs);
}).catch((e) => res.status(404).send(e));
})
When I send the post request from postman, it does not result in an error, but it gives this:
{
"_id" : ObjectId("5b8a3280924c2d0dea15a1df"),
"month" : "September",
"year" : 2018,
"categories" : [
{
"_id" : ObjectId("5b8a3280924c2d0dea15a1e0"),
"sub_categories" : []
}
],
"__v" : 0
}
I can't seem to figure out the issue. Please help.

NodeJS with mongoose: E11000 duplicate key error collection

This is the story: new to NodeJS > trying to seed a mongoDB database using mongoose > need help.
I have two collections: Users (or players) and Teams.
Seed goal: to create some Users and then create some Teams, populated with some of those Users.
Here is my User schema:
var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var UserSchema = new mongoose.Schema({
name: String,
username: String,
password: String
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
Here is my Team schema:
var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var TeamSchema = new mongoose.Schema({
name: String,
users: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
]
});
TeamSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Team", TeamSchema);
And this is the seeding attempt:
var mongoose = require('mongoose');
function seed(collectionName, data, schema){
schema.remove({}, function(err){
if(err){
console.log(collectionName + ".remove: " + err);
} else {
console.log("All " + collectionName + " collection removed");
data.forEach(function(dt){
schema.create(dt, function(err, newData){
if(err){
console.log(collectionName + ".create: " + err);
} else {
console.log(collectionName + " added: " + newData.name);
}
});
});
}
});
}
function seedDB(){
var userData = require('./data/userData'),
userSchema = require('../../models/user');
seed("User", userData, userSchema);
var teamData = require('./data/teamData'),
teamSchema = require('../../models/team');
seed("Team", teamData, teamSchema);
};
module.exports = seedDB;
Yes, I tried to encapsulate the seed function, so I could use it in every collection I would possibly want to seed (in fact, I believe this is the problem).
userData:
module.exports = [
{
name: "Name1",
username: "nickname1",
password: "pass"
},
{
name: "Name2",
username: "nickname2",
password: "pass"
}
];
teamData:
module.exports = [
{
name: "Team1",
users: [
{ "_id" : "594497aa0a403b183ce7e485", "name" : "Name1", "username" : "nickname1", "password" : "pass", "__v" : 0 },
{ "_id" : "594497aa0a403b183ce7e486", "name" : "Name2", "username" : "nickname2", "password" : "pass", "__v" : 0 }
]
},
{
name: "Team 2",
users: [
{ "_id" : "594497aa0a403b183ce7e485", "name" : "Name1", "username" : "nickname1", "password" : "pass", "__v" : 0 }
]
}
];
When I run seed(), I get this error message:
Team.create: WriteError({"code":11000,"index":0,"errmsg":"E11000 duplicate key error collection: pastinha2.teams index: username_1 dup key: { : null }","op":{"name":"Team 2","_id":"5944afd68157e62190ec1919","users":["594497aa0a403b183ce7e485"],"__v":0}})
As far as I could understand, the problem is the order things are being executed, since the query calls are asynchronous. Not sure if this is really the issue, but if it is, how can I prevent it from happening?
Sorry for the long post, but I found several threads with similar problems, and I'm still really stuck here. Could use some help.
Thanks in advance.
you should use Seedgoose instead. It supports smart references. In this case, it won't cause conflict error for you.

mongoose find by ObjectId

I'm defining a mongoose schema like this
var accountPostSchema = new mongoose.Schema({
account: {
id: { type: mongoose.Schema.Types.ObjectId, ref: 'Account' }
},
post: {
id: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' }
}
});
app.db.model('AccountPost', accountPostSchema);
When a user(account holder) create a post, I save the post in a Post schema and get the 'postId'. Then I save the 'postId' and the 'accountId'
in the above accountPostSchema like this
var fieldsToSet = {
post: {
id: postId
},
account: {
id: accountId
}
};
db.models.AccountPost.create(fieldsToSet, function(err, accountPost) {
if (err) {
// handle error
}
// handle success
});
After entering few postId's and accountId's, I see the following results in the mongo shell
> db.accountposts.find({})
{ "_id" : ObjectId("5835096d63efc04da96eb71e"), "post" : { "id" : ObjectId("5835096d63efc04da96eb71d") }, "account" : { "id" : ObjectId("5833c920c868d7264111da69") }, "__v" : 0 }
{ "_id" : ObjectId("583509e12052c7a2a93c4027"), "post" : { "id" : ObjectId("583509e12052c7a2a93c4026") }, "account" : { "id" : ObjectId("5833c920c868d7264111da69") }, "__v" : 0 }
Now how do I find all the matching 'Posts' given an accountId? (not the postId's)
For example if I the accountId is 583509e12052c7a2a93c4026, I need to find Posts with Post._id=5835096d63efc04da96eb71d and Post._id=583509e12052c7a2a93c4026
What is the query I should run to get the matching Posts?
I think, you should follow this way to get all the posts associated with particular accountid.
db.accountposts.find({'account.id' : accountId})
.populate('post.id')
.exec();
First, I would suggest changing your Schema to the following
var accountPostSchema = new mongoose.Schema({
account: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Account'
},
post: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
});
This actually makes more sense, especially when you try to populate the subdocuments. Actually, I would say this Schema is useless. Why don't you define your Post schema like the following?
var PostSchema = new mongoose.Schema({
poster: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Account'
},
message: String
});
If you use the latter code, you could execute the following query to get all posts by a particular user:
db.posts.find({poster: accountId}, function(dbErr, userPosts) {
if(dbErr) {
// Handle the error.
}
// Do something with the posts by accountId in the array userPosts.
});
The advantages of removing the id field from poster becomes clear once you try to populate poster. If you defined poster as an object with the field id and try to populate it, you will need to access data about the poster as such:
posterName = retrievedPost.poster.id.name;
Alternatively, by just making the poster field an ObjectId directly, you can access the populated user more directly:
posterName = retrievedPost.poster.name;

How to update array in mongodb using mongoose

when i try to update it dose not throw back any error it goes OK but when i check my datebase nothing i their updated nothing is modified pls help
this is my db
{
"_id" : ObjectId("56651f0e4905bd041cad0413"),
"creator" : ObjectId("566299dd17990464160ae27a"),
"content" : "this is my joke 2",
"created" : ISODate("2015-12-07T05:54:22.858Z"),
"__v" : 15,
"comments" : [
{
"posteruserId" : "5665e6867185d87c1e71dbdc",
"postedBy" : "lawrence nwoko",
"postterscomment" : "good joke",
"_id" : ObjectId("56660745f644c2501116acce")
},
{
"posteruserId" : "5665e6867185d87c1e71dbdc",
"postedBy" : "lawrence nwoko",
"postterscomment" : "good joke",
"_id" : ObjectId("56660b6d33c245c012104fdc")
}
]
}
this is my schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var JokesSchema = new Schema({
creator: {type: Schema.Types.ObjectId, ref: 'User'},
content: String,
created:{type:Date, default: Date.now},
comments: [{
text: String,
postedBy: String,
posteruserId :String,
date: String,
postterscomment:String
}]
})
module.exports = mongoose.model('Jokes_db', JokesSchema)
here i my post funtion
api.post('/update', function(req, res) {
// Joke.findById("56651f0e4905bd041cad0413", function (err, meeting) {
Joke.update({_id: "5665e6867185d87c1e71dbdc", 'comments._id' : "56660745f644c2501116acce"},
{'$set': {
'comments.$.postterscomment': "working"
}},
function(err, numAffected) {
if(err){
console.log(err)
}else{
res.json(numAffected)
}
}
);
});
It has been three days of trying to fix this problem but by his grace I have done it without help the problem user that I was not using the right id to make the query thanks for your help guys I hope this helps another user
api.post('/editecomments', function(req, res) {
Joke.update({_id: "56651f0e4905bd041cad0413", 'comments._id' : "56660745f644c2501116acce"},
{'$set': {'comments.$.postterscomment': 'working'}},
function(err, numAffected) {
if(err){
console.log(err)
}else{
res.json(numAffected)
}
}
);
});

Resources