using $set on db.collection.save - mongodb

I'am trying to add to date fields and some user info fields to a document, when inserting it into mongo (using db.collection.save).
Here is my code:
collection.save(
{document},
{
$set: {
"document.createdBy": "2",
"document.updatedBy": "2",
"document.created": new Date(),
"document.updated": new Date()
}
},
(err, result) => {
if (err){
res.status(500).json({ status: 'something is wrong' })
//return next(err);
}else{
res.status(200).json({ status: 'ok' })
//return next();
}
});
Mongo only inserts the document and none if the fields in the $set. Any ideas to what I'am doing wrong?

There is no argument for the $set operator in .save() query in mongodb
So instead try to append the object before the query
document.createdBy = "2",
document.updatedBy = "2",
document.created = new Date(),
document.updated = new Date()
collection.save(document, (err, result) => {
if (err){
res.status(500).json({ status: 'something is wrong' })
//return next(err);
} else {
res.status(200).json({ status: 'ok' })
//return next();
}
})

Related

MongoDB find between the dates

I've got the next data in the MongoDB:
{
...
name: Alex,
createdAt: {"$date":"2021-03-09T20:01:57.488Z"},
...
}
And I try to implement the range date query like this:
MongoClient.connect(url, (err, db) => {
if (err) {
return reject(err);
}
const dbo = db.db('dbname');
dbo.collection('users').find({
createdAt: {
$gte: new Date(dateFrom).toISOString(),
$lt: new Date(dateTo).toISOString()
}
}).toArray(
(err, res) => {
if (err) { return reject(err); }
db.close();
return resolve(res);
});
});
And always have zero-result without errors..
How coud I do the right query?

Mongoose find between dates, order by ID

So I am trying to find all documents in a database between 'X' and 'X' dates and then order those by userID. This is what I have so far:
await Expense.find(
{'date' :{'$gte': new Date(startDate), '$lte': new Date(endDate)}}),{sort: {_id: 1}}.exec(function(err, data){
if(err){
console.log('Error Fetching Model');
console.log(err);
}
console.log(JSON.stringify(data, null));
expenseArray = data;
console.log(expenseArray);
But it keeps giving me "TypeError: {(intermediate value)}.exec is not a function"
For added clarification I am trying to write this in mongoose:
"SELECT employeeName, SUM(amount)
FROM reimbursements
WHERE d8 BETWEEN '$startDate' AND '$endDate'
GROUP BY employeeName
ORDER BY employeeName;";
What am I doing wrong? Thank you in advance :D
Your query has few syntax issues, Please try this :
Update :
Below old code will work, but it would be better if you try this way :
try {
let data = await Expense.find(
{ 'date': { '$gte': new Date(startDate), '$lte': new Date(endDate) } }).sort({ _id: 1 })
/** .find() will not return null, it will either return [] or [with matched docs] */
if (data.length) { // checks data != []
console.log(data)
} else { // data == []
console.log('Empty - no docs found')
}
} catch (error) {
console.log('Error Fetching Model');
console.log(error);
}
Old :
await Expense.find(
{ 'date': { '$gte': new Date(startDate), '$lte': new Date(endDate) } }).sort({ _id: 1 }).exec(function (err, data) {
/** sort is not an option for .find() not like aggregate, it has to be on cursor which is result of .find() & .exec() should be at end which is either .find() or .sort() */
if (err) {
console.log('Error Fetching Model');
console.log(err);
}
console.log(JSON.stringify(data, null));
expenseArray = data;
console.log(expenseArray)
})
Sample : mongooseModel.find().sort().exec()
Ref : cursor.sort

mongoose findOneAndUpdate query

I am using mongoose for mongodb queries.
My update query returns null.
What am I doing wrong?
The query is as follows:
Model.findOneAndUpdate(criteria, updatedDetails, { 'new': true})
Example -
I have a user profile which I need to update and send the updated profile back to frontend.
User.findOneAndUpdate({mobile: "9999999999999"}, { address: "test address" }, {'new': true} )
But the result comes null instead of the updated profile.
findOneAndUpdate is now desprecated
use update, here is sample code
exports.updateSomething = (req, res) => {
Model.update({
_id: req.params.id
}, {
$set: {
bla: req.body.bla
}
})
.then(data => {
return res.status(200).json({
success: true,
message: 'Updated successfully'
})
})
.catch(err => {
return res.status(200).json({
success: false,
message: err.message
})
})
}

Nested query in Mongo not working in Meteor

I have some trouble making queries inside a callback running in Meteor Mongo. Anyone is seeing what I am doing wrong here? Thanks!
var houseInserted = Houses.insert({
building_number: address.building_number,
},function(error, results){
if(error) throw error;
console.log(results); // runs
Meteor.users.update( { _id: this.userId }, // Does not execute
{ $set: { 'profile.housed': true , 'profile.address' : results }
}, function(err, doc){
if (err) throw err;
console.log(results); // runs
console.log(doc);
});
console.log(results); // runs
}
);

findAndModify with remove true not removing whole document

Using monk:
var doc =
yield new Promise(function (resolve, reject) {
tokens.findAndModify({
query: {
token: myTokenVar
},
remove: true,
new: false
}, function (err, res) {
if (err)
throw err;
resolve(res);
});
});
The following code above removes every field from the given document but however leaves the document with only the _id field left. It does not completely remove the document.
According the findAndModify source code, the opts object must be provided as a separate parameter. Please try it with the following codes
tokens.findAndModify(
{ query: {
token: myTokenVar
}},
{remove: true, 'new': false},
function (err, res) {
if (err)
console.log(err);
else
console.log(res);
});