How do i push items into a Express.js scheme - mongodb

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
}

Related

Mongoose - Update/Find Specific Object in an Array Not Working As Expected

I am following the docs without luck and am at a standstill while trying to update an object in an object in an array using MongoDB and Mongoose.
Here is my document:
{
fields: [
{ id: 603d63086db2db00ab09f50f, data: [Object] },
{ id: 603d63086db2db00ab09f510, data: [Object] },
{ id: 603d63086db2db00ab09f511, data: [Object] },
{ id: 603d63086db2db00ab09f512, data: [Object] },
{ id: 603d63086db2db00ab09f513, data: [Object] },
{ id: 603d63086db2db00ab09f514, data: [Object] },
{ id: 603d63086db2db00ab09f515, data: [Object] }
],
layouts: [],
_id: 603d631a6db2db00ab09f517,
bandId: '603d63146db2db00ab09f516',
eventType: 'private',
ownerId: '6039354906410800c14934c1',
__v: 0
}
I am trying to updateOne of the fields.data in the fields array. fields.data is an object as well.
I call my Express/Node Backend to this route.
//Update
router.put("/:id", async (req, res) => {
try {
let updating = await QuoteGenerator.updateOne(
{ _id: req.params.id, "fields.id": req.body.id },
{
"$set": {
"fields.$.data": req.body.data,
},
}
);
let item = await QuoteGenerator.findOne({ _id: req.params.id });
res.json({ success: "Item Updated.", item });
} catch (err) {
console.log(err);
res.json({ error: "Something went wrong when updating this item." });
}
});
Where req.body is:
{ id: '603d63086db2db00ab09f50f', data: { type: 1, rate: '200.30' } }
**Just in case it's helpful, here is what one of the fields objects looks like in the document,
{"id":"603d63086db2db00ab09f50f","data":{"type":1,"rate":300}}
I have even tried changing my route to find this document - which I have confirmed exists - Truly at a loss why it won't find the document.
Here is how I changed the above route to find the document.
//Update
router.put("/:id", async (req, res) => {
try {
let updating = await QuoteGenerator.find(
{ _id: req.params.id, "fields.id": req.body.id },
);
console.log(updating) //returns []
let item = await QuoteGenerator.findOne({ _id: req.params.id });
res.json({ success: "Item Updated.", item });
} catch (err) {
console.log(err);
res.json({ error: "Something went wrong when updating this item." });
}
});
The Model
//Create Schema - QG
const QuoteGeneratorSchema = new Schema({
bandId: {
type: String,
required: true,
},
ownerId: {
type: String,
required: true,
},
fields: {
type: Array,
default: defaultFields,
required: true,
},
eventType: {
type: String,
required: false,
},
layouts: {
type: Array,
required: false,
},
});
let QuoteGenerator = mongoose.model("QuoteGenerator", QuoteGeneratorSchema);
module.exports = QuoteGenerator;
Any nudge in the right direction to replacing that data object with a new data object would be extremely helpful! Thanks!

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.

How to get Specialization name from MongoDb

i have such schema of sities in mongoDB
const CitiesSchema = new Schema({
name:{ type:String }
id:Object.id
});
and have such user schema
const UserSchema = new Schema({
name: { type:String, default:'' },
surname: { type:String, default:'' },
foreName: { type:String, default:'' },
email: { type:String, default:'', unique:true },
password: { type:String, default:'' },
phone: { type:String, default:'' },
role: { type:String, default:'' },
profileImg: { type:String, default:'/images/profile.png' },
createdAt: { type:Date, default:Date.now },
city: { type: Schema.Types.ObjectId, ref: 'Story' }
}, { strict: false });
how can i get City name together with user like this :
{
name:'xxxxx',
surname:'xxxxx',
city:'xxxxx' // not Object id, but name
......
}
thanks a lot !!!!
You can use mongoose population to replace the city key in the result of your query with an object in your cities collection instead of a reference. So if you write your user query like this:
User
.findOne({ name: 'Jane' })
.populate('city')
.exec(function (err, user) {
if (err) return handleError(err);
console.log('The user lives in %s', user.city.name);
// prints "The user's lives in Amsterdam"
});
You'll get the city's name in user.city.name.

Mongoose ".select" option strange behaviour

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?

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();
});
});
});
});
});