how to add new field with many data in that field in MongoCosmosDB - mongodb

I would like to add new field into json already have in mongoDB Cosmos like this
{
"_id" : "6396cde306fd2d1088d584e4",
"userName" : "user-20526"
}
Now I would like to add a others field like this bellow userName field:
{
"_id" : "6396cde306fd2d1088d584e4",
"userName" : "user-20526",
"others": [
{
"address" : "city",
"phone" : "12345676543"
}
]
}
I user this function to do that thing, with updateDocument but it's not works for me:
const updateDocuments = async (value, condition, collectionName) => {
const DATABASE_COLLECTION_NAME = collectionName;
if (!db)
throw Error('findDocuments::missing required params');
const collection = await db.collection(DATABASE_COLLECTION_NAME);
const filter = { condition };
const filterJSON = JSON.parse("{" + filter.condition + "}");
const options = { upsert: true };
// get value (condition) and convert it to correct JSON format before call it in update variable
const getValue = { value }
const valueJSON = JSON.parse("{" + getValue.value + "}");
const updateDoc = {
$set: valueJSON
};
return await collection.updateOne(filterJSON, updateDoc, options);
}
The above function only works when we update one field that already have in data, the example I would like to update userName data, then that function is work, If I use that function to add new one then it's not, not add new one, how can I create more to add new field as what I expected before
anyone please help me

Related

Assign new key and value to object does not work

Assign new key and value to object does not work
Here is the post where i would like to add a new key name CreatedUser and wanted to assign object/array but it does not work. Please help on it
here is my code
newPost = new PostsModel({
title,
content,
price,
recreater
});
}
await newPost.save();
let aggregateMatch = null;
let user = null;
if(recreater) {
aggregateMatch = { $match: { _id: ObjectId(recreater) } };
user = await UsersModel.aggregate([
{
$sort: {
timestamp: -1
}
},
aggregateMatch
])
newPost.createdUser = user;
}
console.log("posts", newPost) //Did not see createdUser key
res.out(newPost);
You can't add properties to mongoose document. You have to make it native JS object first.
const post = newPost.toObject();
post.createdUser = user;

ValidationError: user: Cast to Embedded failed for value "[]"

I am trying to insert a new message into the database using expressjs and mongoose.
But I'm getting a ValidationError in the process. The following is printed at the console.
error while storing message ::: ValidationError: user: Cast to
Embedded failed for value "[]" at path "user"
The code is as follows:
socketAPI.io.on('connection', function(socket){
socket.on('chat-sent', function(param) {
ChatUser.find({username : param.username}).then(async (usr)=>{
if(usr){
try{
var mess = new GroupMessage();
mess.group = (await Group.findOne({name : groupName}));
mess.message = param.message;
mess.user = usr;
mess.save((err)=>{
if(err){
console.log('error while storing message ::: '+err);
}
else{
console.log('message succesfully stored');
}
});
}catch(err){
console.log('error collecting group ::: '+err);
}
}
});
socket.emit('group-message-handled', { user : param.username, message : param.message});
});
});
The insertion code makes use of the following models:
var userSchema = new mgoose.Schema({
username : {
type : String,
required : true,
unique : true,
maxlength : [15, 'Too long username. Max 15 allowed']
},
name : String
});
var groupSchema = new mgoose.Schema({
name : {
type : String,
required : true,
unique : true
},
categories : [String]
});
var groupMessageSchema = new mgoose.Schema({
user : userSchema,
group : groupSchema,
message : {
type : String,
required : true,
minlength : 1
}
});
var ChatUser = mgoose.model('ChatUser', userSchema);
var Group = mgoose.model('Group', groupSchema);
var GroupMessage = mgoose.model('GroupMessage', groupMessageSchema);
What causes this error and how can I fix it?

UPDATED WITH FIX: Is there a way to loop an object and save/update a mongodb document on each iteration without getting ParallelSaveError?

I want to update the mongodb document on every loop but seems not to work. I used map to loop through the object and was getting a
parallelSaveError: Can't save() the same doc multiple times in parallel
So now using async.each to loop through the object but seems mongoose only save once. Code below
const openTrade = await TradeModel.find({
$and: [{ isOpen: true }, { price: { $lte: price } }]
})
.sort("volume")
.where({ userId: { $ne: req.authUser._id } });
trade = async openTrade => {
const buyerInfo = await UserModel.findById(req.authUser._id);
const buyerWallet = await WalletModel.findById(buyerInfo.walletId);
const sellerInfo = await UserModel.findById(openTrade.userId);
const sellerWallet = await WalletModel.findById(sellerInfo.walletId);
buyerWallet.balance = parseInt(buyerWallet.balance) - amountToPay;
sellerWallet.balance = parseInt(sellerWallet.balance) + amountToPay;
await Promise.all([sellerWallet.save(), buyerWallet.save()]);
};
async.forEachOf(openTrade, trade);
So I finally found the issue. I did not make the buyerInfo, sellerInfo and Wallets variable constant. So now it works. Thanks
You can try as below: As according to MongoDB update If the document contains an _id field, then the save() method is equivalent to an update with the upsert option set to true and the query predicate on the _id field.
const openTrade = await TradeModel.find({$and:[{isOpen : true}, {price : {$lte : price}}]}).sort('volume').where({userId : {$ne : req.authUser._id } })
trade = async (openTrade)=>{
buyerInfo = await UserModel.findById(req.authUser._id)
buyerWallet = await WalletModel.findById(buyerInfo.walletId)
sellerInfo = await UserModel.findById(openTrade.userId)
sellerWallet = await WalletModel.findById(sellerInfo.walletId)
delete buyerWallet._id;
delete sellerWallet._id;
buyerWallet.balance = parseInt(buyerWallet.balance) - amountToPay
sellerWallet.balance = parseInt(sellerWallet.balance) + amountToPay
await Promise.all([sellerWallet.save(), buyerWallet.save()])
}
async.forEachOf(openTrade, trade)

MongoDB query - pass the function to the Model.find()

I have issue with querying MongoDB (Mongoose) by passing the function as parameter in Model.find() -> like this Model.find(searchCondition). I hope that you can help me.
// Fetching patients from the database
exports.getPatients = (req, res, next) => {
const criterionSearchCategory = req.query.kriterijumPretrage;
const ageSearchCategory = req.query.kriterijumGodina;
const searchInputValue = req.query.pojamPretrage;
console.log({ [criterionSearchCategory]: { [ageSearchCategory]: Number([searchInputValue]) }});
// Patient search condition, based on selected option from select dropdown
function searchCondition() {
if (criterionSearchCategory == 'undefined') {
return {};
} else if (criterionSearchCategory == 'age') {
return { [criterionSearchCategory]: { [ageSearchCategory] : Number([searchInputValue]) }}
} else {
return { [criterionSearchCategory]: { $in: [ "/^" + searchInputValue + "/i" ]}}
}
}
...
const patientQuery = Patient.find(searchCondition);
getPatients(patientsPerPage: number, currentPage: number, criterionSearchCategory: string, searchInputValue: string, ageSearchCategory: any) {
const queryParams = `?pacijenataPoStranici=${patientsPerPage}&trenutnaStranica=${currentPage}&kriterijumPretrage=${criterionSearchCategory}&pojamPretrage=${searchInputValue}&kriterijumGodina=${ageSearchCategory}`;
this.http
.get<{ message: string, patients: any, maxPatients: number }>( BACKEND_URL + queryParams)
// Execute map on every data that makes it through Observable stream
.pipe(map((patientData) => {
I want to menton when I pass the query params manually, for example const patientQuery = Patient.find({ age: { '$gt': 30 } }); appropriate patients will be fetched correctly , but when I pass the function , like this const patientQuery = Patient.find(searchCondition); then does not work.
The first question, is it possible to pass the function as parameter like this?
Any suggestion will be appreciate. Thank you

Reading mongo collection created outside of meteor

I have a mongo collection that is created outside of Meteor that holds user info of people who want access to my app. It looks like this in MongoVue-
**tmpUsers**
/* 5 */
{
"_id" : ObjectId("54c7ae456587e23335915948"),
"email" : "trial#domain.com",
"first" : "Trial User",
"type" : "trial",
"active" : "Yes"
}
When I try to read this I get basically an empty collection structured like this -
collection:
d_docs: d._IdMap_..........
Here's my code -
**client**
var type = "";
var tmpCursor = tmpUsers.find({"email": Meteor.user().emails[0].address});
tmpCursor.forEach(function(rec) {
type = rec.type
});
Meteor.call("updateProfile", Meteor.userId(), type);
**server**
Meteor.methods({
"updateProfile": function(id, value){
Meteor.users.update({"_id": id}, {$set: {"profile.acctType": value}});
}
})
How would I update the client side code to read the type from tmpUsers?
Update:
Here is where I insert the record from outside of Meteor -
try {
$mongoDb = $mongoConn->abcdefg;
$collection = $mongoDb->tmpUsers;
$userInfo = array("email" => $_POST['email'], 'first' => $first,"type" => $_POST['type'], 'active' => $activation);
$collection->insert($userInfo);
} catch (MongoException $e) {
die('Error: ' . $e->getMessage());
}
Try with this.
Tracker.autorun(function(){
Meteor.subscribe('tmpUsers',function(){
var finde = tmpUsers.find({email:Meteor.user().emails[0].address}).count();
if (finde === 1){
console.log("found email");
} else{
console.log("not email found")
}
});
});