Mongoose:Some fields are missing while printing user on console in mongodb - node.js

I have a problem when I am trying to print user on the server console
my code is
var user = new User({userid:userid})
console.log(user)
its printing on the console
{ userid: 'qq', questions: [], _id: 5ad4602efb255e054412acfa }
but in my database I have saved user like this
{ "_id" : ObjectId("5ad4602efb255e054412acfa"), "id" : 0, "userid" : "qq", "password" : "$2a$10$NNqsVSoTs7eWJiLWy0fZN.0P2mMiiYFYRDFVaLJA9fcY53xRM3uLK", "questions" : [ ], "__v" : 0 }
I have five fields in my database
1-_id,
2-id,
3-userid,
4-password,
5-questions[]. But when I am trying to print user on the console its not printing some fields...why?
my schema is
var mongoose = require("../../connection");
var Schema = mongoose.Schema;
var userSchema = new Schema({id:Number,
userid:String,
password:String,
questions:[]
});
var User = mongoose.model("onlineusers",userSchema);
module.exports = User;
and also when I am trying to print console.log(user.id)
its print undefined

Related

mongodb issue when using .find()

I am using MongoDB for the first time and I came across an error that I could not solve.
Here is my code:
const mongoose = require('../../common/services/mongoose.service').mongoose;
const Schema = mongoose.Schema;
const functions = require('./functions');
const userSchema = new Schema({
email: String,
password: String,
number: String,
state: Boolean
});
userSchema.virtual('id').get(function () {
return this._id.toHexString();
});
// Ensure virtual fields are serialised.
userSchema.set('toJSON', {
virtuals: true
});
userSchema.findById = function (cb) {
return this.model('Users').find({id: this.id}, cb);
};
const User = mongoose.model('Users', userSchema);
exports.findByEmail = (email) => {
//console.log('hello'); //this works btw
return User.find({email: email});
};
So in the code above, findByEmail works fine since hello is logged. However, when it gets to return User.find, I get this error: SyntaxError: Unexpected token g in JSON at position 0.
This is what is currently in the DB:
{
"_id" : ObjectId("6026b813f1828a51f8979616"),
"email" : "gogo#gmail.com",
"password" : "GLImDln1xMKfKS/E99s8qg==$Es3PIHD95vV89973Xq4RecveYMEf22PCH/pFtG1+xq4Gtc4DelA/JXlRNcOR11Rfv/J1uaZCuOplsEmHhY0ehQ==",
"number" : "6969",
"state" : true,
"__v" : 0
}
I input gogo#gmail.com. Does anyone know what I am doing wrong? It would mean a lot to me. I am using node/vue btw.
Error occurs within findByEmail when I run it

Mongoose model schema referencing not working

Basically I have 3 mongoose models(user,product,cart).I have tried referencing cart model with user model.I've the used populate method in mongoose to populate the referenced property in the model.But it is not working and I'm getting an empty cart array after adding a product to the cart like this on consoling.
{
"_id": "5a0b2dcf726753258002273d",
"password": "12345",
"securityQuestion": "What is your Nick Name?",
"securityAnswer": "rj1",
"__v": 0,
"cart": [], // empty cart here
"mobileNumber": 1234567890,
"email": "rahul#gmail.com",
"lastName": "jhawar",
"firstName": "rahul",
"userName": "rj"
}
I also wanted to know whether my referencing of models are done correctly(I mean the relationship).
I'm new to this concept.Please help me out.
//Cart.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var cartSchema = new Schema({
productName : {type:String,default:''},
productCategory : {type:String,default:''},
productDescription : {type:String,default:''},
productPrice : {type:String,default:''},
sellerName : {type:String,default:''},
});
module.exports=mongoose.model('Cart',cartSchema);
//User.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
userName : {type:String,default:'',required:true},
firstName : {type:String,default:''},
lastName : {type:String,default:''},
email : {type:String,default:''},
mobileNumber : {type:Number,default:''},
password : {type:String},
securityQuestion : {type:String},
securityAnswer : {type:String},
cart : [{
type: Schema.Types.ObjectId,
ref:'Cart'
}]
});
module.exports=mongoose.model('User',userSchema);
///Routes///
const cartRouter = express.Router();
const cartModel = mongoose.model('Cart');
const userModel = mongoose.model('User');
const productModel = mongoose.model('Product');
cartRouter.get('/addtocart/:id',auth.checkLogin,(req,res)=>{
productModel.findOne({'_id':req.params.id},(err,foundProduct)=>{
if(!err){
const newCartProduct = new cartModel({
productName : foundProduct.productName,
productCategory : foundProduct.productCategory,
productDescription : foundProduct.productDescription,
productPrice : foundProduct.productPrice,
sellerName : foundProduct.sellerName
});
newCartProduct.save((err)=>{
if(!err){
userModel.findOne({'_id':req.session.user._id}).populate('cart')
. exec((err,cartproduct)=>{
console.log(JSON.stringify(cartproduct, null, "\t"));
});
console.log('New Product added to cart');
res.redirect('/users/cart_products');
}
});
});
});
You've correctly set up the relationship between the user and the cart models in that the user potentially holds a reference to a number of cart models.
However, when you save the cart, you aren't actually updating the cart array/property of the user. You have to both save your newCartProduct and you also have to push the resultant id into the cart array and then save your user model. If you don't do this the populate method isn't going to work, since it has nothing to populate.
Here's an example of how you might use findByIdandUpdate to update the user with the new cart item.
cartRouter.get('/addtocart/:id',auth.checkLogin,(req,res)=>{
productModel.findOne({'_id':req.params.id},(err,foundProduct)=>{
if(!err){
const newCartProduct = new cartModel({
productName : foundProduct.productName,
productCategory : foundProduct.productCategory,
productDescription : foundProduct.productDescription,
productPrice : foundProduct.productPrice,
sellerName : foundProduct.sellerName
});
newCartProduct.save((err, o)=>{
if(!err){
userModel.findByIdAndUpdate(req.session.user._id,
{$push: {"cart": o._id}},
{safe: true, new : true})
.populate('cart')
.exec((err, model) => {
console.log(model); //This will have the cart array filled in
});
});
});
Other choices would be either to reverse the relationship, to hang the reference to the user from the cart, or to use an embedded subdocument:
cart: [Cart]
If you never need to access cart entries outside of the context of a single user (if you never need aggregate information across users), then it's probably the right thing to do.
Your approach maybe right for your use cases, but then you have to manually maintain both sides of the relationship when items are added and removed from the cart.

How can I query whether an objectID is in an array in MongoDB with Node.js?

This is how my model looks like in Mongo:
{
"_id" : ObjectId("5951552c5bb94058b203d3e3"),
"roleName" : "Bartender",
"userList" : [
ObjectId("5926ff5088a3da5bf0d3d43b")
],
"deadline" : ISODate("2017-06-26T18:40:44.153Z"),
"__v" : 1
}
I would like to query 2 things together.
1, -Show me the model of the "role" I'm looking for.
2, -Give me true or false depending on whether the user's ID is to be found in the userList array.
exports.roleView = function(req,res, next){
const userID = req.params.userId;
const roleID = req.params.roleId;
const findUser = Role.findById({ _id: roleID
}).populate('userList', 'userName')
.then((result)=>{return result})
.catch((err)=>{return err});
const userinRole = Role.findOne({
_id:roleID, userList: userID})
.then((result)=>{return true})
.catch((err)=>{return false});
return Promise.all([findUser, userinRole])
.then((role)=>{
res.json(role);
});
};
Yet, every time don't have a match in userinRole, Mongo would just simply freeze without response.
Is it actually the proper way, or would you approach it differently? Thank you so much!

Mongoose returns empty while the same query in mongodb shell works fine

I know maybe this question has been asked quite many times here, I've went through several solutions people came with to similar questions but none of them seemed to help in my case.
I have two collections called users and posts and models for them look like this:
users
var mongoose = require('mongoose').set('debug', true);
var Schema = mongoose.Schema;
var usersSchema = new Schema({
name: {type: String, required: true}
});
var User = mongoose.model('user', usersSchema, 'users');
module.exports = User;
posts
var mongoose = require('mongoose').set('debug', true);
var Schema = mongoose.Schema;
var postsSchema = new Schema({
content: String,
user: {
type: Schema.ObjectId,
ref: 'users',
required: true
}
});
var Post = mongoose.model('post', postsSchema, 'posts');
module.exports = Post;
I'm trying to get the posts of a user using this code:
var Post = require('../models/posts');
...
router.get('/posts/user/:userId', function (req, res, next) {
Post.find({user: req.params.userId}, function (err, posts) {
Post.populate(posts, {path: 'user'}, function(err, posts) {
res.send(posts);
});
});
});
Mongoose debug mode reports that the following query is executed during the request:
posts.find({ user: ObjectId("592e65765ba8a1f70c1eb0bd") }, { fields: {} })
which works perfectly fine in mongodb shell (I'm using Mongoclient) but with Mongoose this query returns an empty array.
The query I run in mongodb shell:
db.posts.find({ user: "592e65765ba8a1f70c1eb0bd" })
The results I get:
{ "_id" : ObjectId("592e66b48f60c03c1ee06445"), "content" : "Test post 3", "user" : "592e65765ba8a1f70c1eb0bd" }
{ "_id" : ObjectId("592e66b98f60c03c1ee06446"), "content" : "Test post 4", "user" : "592e65765ba8a1f70c1eb0bd" }
{ "_id" : ObjectId("592e66bb8f60c03c1ee06447"), "content" : "Test post 5", "user" : "592e65765ba8a1f70c1eb0bd" }
I'm at the very beginning on learning Node.JS and MongoDB, so maybe I've missed something.
Thank you in advance!
As Neil Lunn suggested, I checked the user field type and it was indeed of type String instead of ObjectId so there was a mismatch of types between the data stored in collection and the field type from the query.
I used this code to convert the user field type from String to ObjectId in my collection:
db.getCollection('posts').find().forEach(function (post) {
db.getCollection('posts').remove({ _id : post._id});
tempUserId = new ObjectId(post.user);
post.user = tempUserId;
db.getCollection('posts').save(post);
}
);
Now everything works as expected.

How do I perform a find query in Mongoose?

i have a collection of Ebooks data in mongodb like
{
"_id" : ObjectId("58b56fe19585b10cd42981d8"),
"cover_path" : "D:\\Ebooks\\uploads\\ebooks\\cover\\1488285665748-img1-700x400.jpg",
"path" : "D:\\Ebooks\\uploads\\ebooks\\pdf\\1488285665257-Webservices Natraz.pdf",
"description" : "ebook",
"title" : "book name",
"tag" : [
"Hindi",
"Other"
],
"__v" : NumberInt(0)
}
Now i want to search something if keyword is little bit match from "title:" then show all related books object.
My Mongoose schema is :-
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var EbookSchema = new Schema({
title: {type:String},
description: {type:String},
path: {type:String,required:true},
cover_path: {type:String,required:true},
tag: [{ type: String }]
});
module.exports = mongoose.model('Ebook', EbookSchema);
I try :-
app.get('/ebook?search=',function(req,res){
var search_key = req.param('search');
Ebook.find(title:'search',function(err, ebooks) {
if (err)
res.send(err);
res.json(ebooks);
});
});
but i found null how can i do ? i only want when i search a little-bit keyword i found all related object .
Try wrapping your query in curlies, Mongoose expects an object as the query.
app.get('/ebook?search=',function(req,res){
var search_key = req.param('search');
Ebook.find({title: search_key})
.then(ebooks => res.json(ebooks))
.catch(err => res.status(404).json({ success: false }));
});

Resources