mongoose db populate doesn't seem to work - node.js

So this is how my models are:
groupModel.js
var Schema = mongoose.Schema;
var groupSchema = new Schema({
uuid: String,
users: [{type: Schema.Types.ObjectId, ref:'users'}]
});
var Groups = mongoose.model('groups', groupSchema);
module.exports = Groups;
userModel.js
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var userSchema = new Schema({
username: String,
password: String,
firstname: String,
lastname: String,
email: String,
emailVerified: Boolean
});
var Users = mongoose.model('users', userSchema);
module.exports = Users;
and this is the api I am hoping to get it to work:
/* GET /group/list/:id listing. */
router.get('/list/:id', function(req, res) {
Group.findOne({uuid :
req.params.id}).populate('Users').exec(function(err, group){
if(err) throw err;
console.log(group);
res.status(200).send(group);
});
});
this is the response I get back:
{"_id":"5aaf52b4165e97aae4a0b42c","uuid":"iyzIc","__v":0,"users":
["58f5acae4733ae5f64XXXXea","590a663c2a32ad28e0XXXX29"]}
For some reason I am not able to replace the id's with actual data for the users. I was hoping to get user related details instead of ids for the two users. Am I doing something wrong? I am trying to learn nodejs and was hoping some nodejs expert will be able to find my silly mistake.
EDITED:
changing .populate('Users') -> .populate('users') fixed the issue.

Users being capitalized in populate is the problem!

Related

Mongoose Find By Ref ID

so I have two schemas, User und Company
const UserSchema = new mongoose.Schema({
_createdAt: Date,
company: {type: mongoose.Schema.Types.ObjectId, ref: 'company'},
email: String,
});
const CompanySchema = new mongoose.Schema({
_createdAt: {
type: Date,
required: true
},
name: {
type: String,
required: true
}
});
const userModel = mongoose.model("user", UserSchema, "user");
const companyModel = mongoose.model("company", CompanySchema, "company");
I would now like to query for a specific User by his Company _id, but for some reason this is not working, it returns an empty array even though I have a user with the exact company ObjectId in my Database.
userModel.find({company: "5cfa4352ffc1c8135d8276a4"})
.exec((err, user) => {
console.log(user);
}
In my mongo shell the command
db.user.find({company: "5cfa4352ffc1c8135d8276a4"})
returns the users as expected so why does this not work in mongoose? Thanks in advance
Try this
const ObjectId = require('mongodb').ObjectID;
then
db.user.find({company: ObjectId("5cfa4352ffc1c8135d8276a4")})
I hope it will work
If you want to find by that id you probably need to do this:
const mongojs = require('mongojs');
const ObjectId = mongojs.ObjectId;
db.user.find({company: ObjectId("5cfa4352ffc1c8135d8276a4")})
Since you are using moongose, you can get the ObjectId like this:
const mongoose = require('mongoose');
const objectId = mongoose.Types.ObjectId('569ed8269353e9f4c51617aa')

Multiple schema in a file not working

I have two schema in singel schema.js file
var mongoose = require('mongoose');
var user = new mongoose.Schema({
name: String,
add: String,
role: String
});
var Organizationn = new mongoose.Schema({
name: String,
add: String,
name:String
});
module.exports = {
user: user,
Organizationn: Organizationn
};
accessing it like
var models = require("../models/schema");
models.user.findOne()
it says findone is not a function
whereas If i use singel user in a file it is working.
I have gone through this link and did export like above
cant get data from database after multiple schema declared (mongoose + express + mongodb
but not working
any idea?
Thanks
With the help of #anthony I figure out the issue
I need to do the below
module.exports = {
user: mongoose.model('user', user),,
Organizationn: mongoose.model('Organizationn', Organizationn)
};
If you exports more than one file than you will have to import with curly braces { schema1 }
var mongoose = require('mongoose');
var user = new mongoose.Schema({
name: String,
add: String,
role: String
});
var organization = new mongoose.Schema({
name: String,
add: String,
name:String
});
const userSchema = mongoose.model('users', user),
const organizationSchema = mongoose.model('organizations', organization)
module.exports = { User: userSchema, Organization: organizationSchema }
and then import
var { User } = require("../models/schema");
var { Organization } = require("../models/schema");
User.findOne()
Organization.findOne()
Try to look at it in this abstract way:
A mongoose.Schema is basically just an object.
A mongoose.model is a class that you customize with your schema object.
In other words, mongoose.model has all the database functions attached to it, the schema by itself doesn't.

MongoError: E11000 duplicate key error

i'm making a simple blog app using nodejs + express, i can add first post without a problem but when i try to add second post i got his error { MongoError: E11000 duplicate key error collection: restful_blog_app_v2.blogs index: username_1 dup key: { : null }
this is my schema
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
type: Date,
default: Date.now
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
BlogSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Blog", BlogSchema);
this is the user schema
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String,
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
this is the create new post route
app.post("/blogs", isLoggedIn, function (req, res) {
req.body.blog.body = req.sanitize(req.body.blog.body);
var title = req.body.blog.title;
var image = req.body.blog.image
var body = req.body.blog.body;
var created = req.body.blog.created;
var author = {
id: req.user._id,
username: req.user.username
}
var newPost = {
title: title,
image: image,
body: body,
created: created,
author: author
}
Blog.create(newPost, function (err, newBlog) {
if (err) {
console.log(err);
res.render("new");
} else {
console.log(newBlog);
res.redirect("/blogs");
}
});
});
I've tried to dropped the entire database using db.dropDatabase() from the mongo console but the problem still persist, not sure what to do now
This is caused by passport-local-mongoose, which, according to its fine manual, makes username a unique field by default.
You have added this plugin to BlogSchema, which seems like you initially had the user data in that schema but moved it to a separate schema (UserSchema) and forgot to remove it from the former.
Start by not using it for BlogSchema, and you also need to drop the unique index on username on the blogs collection.
Can you try deleting your Schema and again send the value? I was getting the same issues. I solved with the above idea.

Populating count of records from other collection with Mongoose

I have 2 Mongoose models, Book and Users. i want to do that: When find a book, i want to get the count of current book users.
this is book model:
var mongoose = require('mongoose');
var Users = require('../users');
var schema = new mongoose.Schema({
book_name: String,
book_publisher: String
});
var book = mongoose.model('book', schema);
module.exports = book;
this is users model:
var mongoose = require('mongoose');
var Book = require('../book');
var schema = new mongoose.Schema({
user_name: String,
book_id: String
});
var users = mongoose.model('users', schema);
module.exports = users;
i fetch a book like this:
Book.find({book_name:name).exec(
function(err, book) {
if (err) {
throw err;
}
var new_book = book;
}
);
right now tis code fetch a book, but i want to populate count of users inside Users model and add them to the new fetched book object.
i read this document but i can't accomplish that:
Population
User = new mongoose.Schema({
//existing user properties
owned_books: [{type: mongoose.Schema.Types.ObjectId, ref: 'book'}]
}}
var users = mongoose.model('users', User);
var schema = new mongoose.Schema({
book_name: String,
book_publisher: String,
owner_ids: [{type: mongoose.Schema.Types.ObjectId, ref: 'users'}]
});
var book = mongoose.model('book', schema);
You'll need to update both schema when you add people to books or books to people. To get the current book users, just find the book and then get length of it's owner_ids field.
What you want to do is usually known as reverse lookup. Luckily, someone has already created a module for that. It doesn't seem like its a very commonly used module, but you could see if it fits your needs: reverse-populate.

Why are some of my mongoose models not loading? Apparently they're not there

I'm loading my mongoose models and some of them load, while others apparently don't load at all.
For instance,
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
var Friend = require('../models/Friends.js');
OR var Friend = mongoose.model('Friends');
If I console.log(Friend). I get an empty object. However, if I console log the other models, they exist. I created them EXACTLY the same way. I've been having some issues creating new mongoose models for some reason. Any ideas?
This is my friends.js file, which is exactly the same as the rest.
var mongoose = require('mongoose');
var FriendSchema = new mongoose.Schema({
firstName: String,
lastName: String,
updateFrequency: Number,
email: String,
pastInteraction: [],
lastTime: Date
});
FriendSchema.methods.updateLastAccess = function(cb){
this.lastTime = new Date();
this.save(cb);
}
mongoose.model('Friends', FriendSchema);
You are not exporting anything from friends.js
Export the Friends model from there
var mongoose = require('mongoose');
var FriendSchema = new mongoose.Schema({
firstName: String,
lastName: String,
updateFrequency: Number,
email: String,
pastInteraction: [],
lastTime: Date
});
FriendSchema.methods.updateLastAccess = function(cb){
this.lastTime = new Date();
this.save(cb);
}
module.exports =mongoose.model('Friends', FriendSchema);
After making this change you can console.log() and check
var Friend = require('../models/Friends.js');
console.log(Friend) ;
Why am I able to access the other models in the same way? I haven't
exported yet I'm able to access them.
because you are creating a model at the spot on same file for them like mongoose.model('Post');

Resources