Mongoose ".select" option strange behaviour - select

Here's my model:
var Account = new Schema({
username: String,
likes: {
users: {type: Schema.Types.Mixed, default: {}},
reviews: {type: Schema.Types.Mixed, default: {}}
},
requests: {
incoming: {type: Schema.Types.Mixed, default: {}},
outgoing: {type: Schema.Types.Mixed, default: {}}
}
}, {minimize: false});
Here's my request:
router.get('/requests', function(req, res, next) {
var id = req.user._id;
var callback = function(err, doc){
if(err) {
next(err);
return;
}
res.send(doc);
}
Account.findById(id)
.select({requests: 1})
.exec(callback)
})
Here's my result:
{
likes:{},
requests: {
incoming:['a','b','c'],
outgoing:['d','f','g']
}
_id: 'KAJDiasjdaiodjwoi43j034345'
}
Why does "likes:{}" show up?

Related

How do i push items into a Express.js scheme

I wonder how can i push an item into an array contained in a Express.js Scheme.
Here is the scheme i am trying to push items into:
const mongoose = require("mongoose") ;
const Post = new mongoose.Schema({
username: {type:String, required:true},
password: {type:String, required:true},
passwordHash: {type:String, required:true},
userOrders: [{orderId: String, orderItem:String}]
}, {
collection: 'users-data'
})
module.exports = mongoose.model("PostAccount", Post)
And my attempt to do it:
userForm.findOneAndUpdate(
{username : usernameDB },
{ $push:{userOrders :{orderId: id, orderItem: item}} },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
});
Also here you can see the output i get:
{
_id: new ObjectId("62c73f91b853f687b507b069"),
username: 'admin3',
password: 'root',
passwordHash: '$2b$10$IEausr.hQzcRcFxhSOPAN.WyNY6gBHWEOr8db7Js3/iitcAC34ple', userOrders: [
{
orderId: null,
orderItem: null,
_id: new ObjectId("62c73f91b853f687b507b06a")
}
],
__v: 0
}

Conditional query mongo db after populate not returning data

I am new in mongo and node and I am facing a problem in filtering.
I have a customer schema and wallet schema. When I am inserting a new
customer it is populating a wallet for that customer. Schema of this
two model is below.
Customer.model.js
var Schema = mongoose.Schema;
const Genders = Object.freeze({
Male: 'male',
Female: 'female',
Other: 'other',
});
var CustomerSchema = new Schema({
reg_date: { type: Date, default: Date.now },
first_name: String,
last_name: String,
gender: {
type: String,
enum: Object.values(Genders),
},
wallet_balance: { type: Number, default: 0 },
status:{type:Boolean,default:true},
wallet:{type:mongoose.Schema.Types.ObjectId,ref:'Wallet'},
customer_rank: String
});
module.exports = mongoose.model('Customer', CustomerSchema);
Wallet.model.js
var Schema = mongoose.Schema;
var TransactionSchema = new Schema({
reason: String,
deposit_by: Number,
transaction_type: String,
transacted_balnace:Number
})
var WalletSchema = new Schema({
user_id:String,
transaction_log: [TransactionSchema],
balance: { type: Number, default: 0 },
created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now }
});
WalletSchema.plugin(uniqueValidator);
module.exports = mongoose.model('Wallet', WalletSchema);
I want to get customer details on basis of reason.
So, the code is below.
CustomerModel.find({}, { "password": 0 }).populate({
path: 'wallet',
match: { reason: { $in: [ "service charge" ] } },
select: 'transaction_log'
}).exec().then(data => {
if (data) {
res.status(200).send({ status: true, data: data })
}
else {
res.send({ status: false, data: [] })
}
})
It is not returning the wallet, But if I remove the match property it
is working fine.It will be very helpful if I get a solution. Thanks
in advance.

Create new subdocument in mongoose

What am I missing here? I want to add a sub document to the User schema I already have the schema predefined else where.
User.findById(req.body.id, function(err, user) {
if (err) return console.log(err);
reivews: [{
reviewer: req.body.name,
content: req.body.content
}]
user.save(function(err) {
if (err) console.log(err);
res.send('saved')
})
})
It's saying its saved but I don't see the review in the for the user with the id I tried to save to.
Schema
const Review = new Schema({
reviewer: String,
date : { type: Date, default: Date.now },
content : String,
isLive : { type: Boolean, default: false }
});
const User = new Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
reviews: [Review]
});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('Review', Review);
module.exports = mongoose.model('User', User);
Please try this
User.findById(req.body.id, function(err, user) {
if (err) return console.log(err);
if (user.reviews === undefined || user.reviews.length == 0) {
user.reviews = [];
}
user.reviews.push({
reviewer: req.body.name,
content: req.body.content
});
user.save(function(err) {
if (err) console.log(err);
res.send('saved')
})
})
And ensure that data in user as per the defined Schema

MongoDB (mongoose) about refs

who can explain with example how to get from another schema user data (for example useravatar)
while i read about refs and i cant understand.
This is my code, but i want to send back not only article but with profile datas about author. How can i do this ? I have authorID already for this.
router.post('/get-article', (req, res) => {
const { id, authorID } = req.body.data;
Article.findByIdAndUpdate({ _id: id }, { $inc: { "pageview": 1 } }, (err, article) => {
if (err) return res.status(400).json({ NotFound: "Article Not Found" })
res.json({ article })
})
})
article schema
const schema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
title: { type: String, required: true },
image: { type: String, required: true },
content: { type: String, required: true },
email: { type: String, required: true },
author: { type: String, required: true, index: true },
added: { type: Date, default: Date.now },
pageview: { type: Number, default: 0 }
});
User schema
const schema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
username: { type: String, required: true },
email: { type: String, required: true },
facebookId: { type: String },
githubId: { type: String },
googleId: { type: String },
useravatar: { type: String, required: true },
userip: { type: String, required: true },
accessToken: { type: String },
date: { type: Date, default: Date.now }
});

How to do inner reference with mongoose?

I want to do something like following code, but it failed.
var User = new Schema({
name: { type: String, required: true },
phone_number: { type: String, required: true },
modified: { type: Date, default: Date.now },
contacts: [{
user: { type : Schema.ObjectId, ref : 'User' }
}]
});
var UserModel = mongoose.model('User', User);
Is it able to achieve that purpose?
I think I used the wrong way to check it, actually it works.
Following is my test :
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('localhost', 'contacts_test');
var User = new Schema({
name: { type: String, required: true },
phone_number: { type: String, required: true },
modified: { type: Date, default: Date.now },
contacts: [
{
user: { type: Schema.ObjectId, ref: 'User' }
}
]
});
var UserModel = mongoose.model('User', User);
mongoose.connection.on('open', function () {
var user1 = new UserModel({name: 'kos', phone_number: "003"});
user1.save(function (err) {
if (err) throw err;
var user2 = new UserModel({name: 'java', phone_number: "008"});
user2.contacts = [{user: user1._id}];
user2.save(function (err) {
UserModel.findById(user2._id)
.populate('contacts.user')
.exec(function (err, user) {
if (err) console.error(err.stack || err);
console.log('user name: ' + user.name);
console.error('contact of first result : ', user.contacts[0].user.name);
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close();
});
});
});
});
});