I want to add dynamic columns in my document but when add new column
it display error, I m using mongoDB 3.4
router.post('/get-personal-information', function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
Employee.update({_id : req.body._id},{$set:{'name1' : 'dsadas'}}, {upsert:true}, function(err, doc){
if (err) return res.send(500, { error: err });
return res.send(doc);
});
});
Error Message ::
{
"error": {
"name": "MongoError",
"message": "'$set' is empty. You must specify a field like so: {$set: {<field>: ...}}",
"driver": true,
"index": 0,
"code": 9,
"errmsg": "'$set' is empty. You must specify a field like so: {$set: {<field>: ...}}"
}
}
i found the solution
Use {strict: false} to modify the columns or make any type of
operation on columns
router.post('/get-personal-information', function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
Employee.update({_id : req.body._id},{$set:{'name1' : 'dsadas'}}, {strict:false}, function(err, doc){
if (err) return res.send(500, { error: err });
return res.send(doc);
});
});
Related
I'm unable to order the result set returned from the allDocs function in PouchDB.
db.allDocs({startKey: "cat_", include_docs: true, orderBy: "category_name"}, function(err, response) {
if (err) return console.log(err);
allCategories = response.rows;
});
I also tried to use sort instead of orderBy but it didn't work.
This is the structure of my documents:
db.put({
"_id": "cat_5601",
"category_name": "Groceries",
"parent_category": null,
"category_vat": 1,
});
Sending a put request by findAndUpdateById which returns a 200 response in postman - but the data is not updated.
The put request is
app.put("/api/report/update/:id", (req, res) => {
Report.findByIdAndUpdate(
req.params.id,
req.body.data,
{ new: true },
(err, report) => {
if (err) return res.status(404).send({ message: err.message });
return res.send({ message: "report updated!", report });
}
);
});
The shape of the data sent is
report: {
month: "",
updateMajor: "",
updateMinor: "",
comments: {
comment1: "",
comment2: "",
comment3: ""
},
}
The data is returned exactly as sent.
Thanks for any help.
you need to use some update operator like $set, $unset, $push etc. in your update query. since you are not using any of those you are getting this behaviour.
If you just want to set the value that you are sending, Try using it with $set.
Try this:
Report.findByIdAndUpdate(
req.params.id,
{$set : req.body.data } ,
{ new: true },
(err, report) => {
if (err) return res.status(404).send({ message: err.message });
return res.send({ message: "report updated!", report });
}
);
Note : $set overrides previous value.
If you need something else, please read detailed information in MongoDB update Operators Documentation
I have a collection named "posts" in a mongodb at mlab.com and I am trying to access all of the documents in this collection with db.collection('posts').find(). Below is my code for my webtask I've created, which I named mongodb_find:
var MongoClient = require('mongodb').MongoClient;
var waterfall = require('async').waterfall;
/**
* #param {secret} MONGO_URL - Mongo database url
*/
module.exports = function(ctx, cb) {
var MONGO_URL = ctx.data.MONGO_URL;
if (!MONGO_URL) return cb(new Error('MONGO_URL secret is missing'))
waterfall([
function connect_to_db(done) {
MongoClient.connect(MONGO_URL, function(err, db) {
if(err) return done(err);
done(null, db);
});
},
function find_hits(db, done) {
db
.collection('posts')
.find(
{},
function (err, result) {
if(err) return done( err );
done( null, JSON.stringify(result) );
}
).sort({ hits: -1 }).limit( 2 );
}
], cb);
};
I have a mongodb_upsert webtask that is very similar to this and works perfectly. However, for my mongodb_find task I am getting the following error:
{
"code": 400,
"error": "Error when JSON serializing the result of the JavaScript code.",
"details": "TypeError: Converting circular structure to JSON",
"name": "TypeError",
"message": "Converting circular structure to JSON",
"stack": "TypeError: Converting circular structure to JSON\n at Object.stringify (native)\n at /data/sandbox/lib/sandbox.js:775:48\n at /data/sandbox/node_modules/async/dist/async.js:473:16\n at next (/data/sandbox/node_modules/async/dist/async.js:5315:29)\n at /data/sandbox/node_modules/async/dist/async.js:958:16\n at /data/io/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/webtask.js:27:6\n at handleCallback (/data/_verquire/mongodb/2.0.48/node_modules/mongodb/lib/utils.js:96:12)\n at Collection.find (/data/_verquire/mongodb/2.0.48/node_modules/mongodb/lib/collection.js:354:44)\n at find_hits (/data/io/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/webtask.js:23:5)\n at nextTask (/data/sandbox/node_modules/async/dist/async.js:5310:14)"
}
When connecting to mongodb from the command line the same find() command works properly:
db.posts.find({}).sort({hits: -1}).limit(2);
The documents in the collection are set up like this:
{
"_id": {
"$oid": "5a3ff239bda4eaa4ab96ef8b"
},
"title": "Testing 6",
"url": "/jquery/2017/12/22/testing-6.html",
"hits": 2
}
Does anyone know of a solution to this issue? Thank you.
Collection.find returns a cursor, not the results of the query. You probably want to chain all your operations such as sort and limit on the cursor, then use toArray to define the callback. toArray will retrieve the results from the cursor.
For example:
function find_hits(db, done) {
db.collection('posts')
.find({})
.sort({ hits: -1 })
.limit(2)
.toArray(function (err, result) {
if(err) return done( err );
done(null, JSON.stringify(result));
});
}
I have an original mongodb collection that looks like this that populates in my app:
{"_id": "57d5af7de3a3885aa7381380", "name": ["Barry Allen", "Bruce Banner",
"Clint Barton",
"Arthur Curry",
null]}
How can I replace my mongodb collection with a javascript array that looks like this:
var newRoster =
["Peter Parker", "Susan Storm", "Victor Stone",
null, "Jennifer Walters];
I tried doing this in my js file.
$.ajax({
method: 'POST',
url: '/students',
data: {
updatedRoster: newRoster,
},
success: function(response){
console.log(response);
if (response == 'success'){
alert('Successfully updated');
} else {
alert('Error');
}
}
});
I tried going this in my node file.
app.post('/students', function(req, res){
db.students.update({"name": req.body.updatedRoster},
function(err, docs){
if (err) throw err
res.send('success');
});
});
The first object in the update function is a selector. It tells mongoDB which document you want to update. The second object is used to tell mongoDB how you want the found document(s) to be changed.
So, try this:
// client
$.ajax({
method: 'POST',
url: '/students',
data: {
_id: id,
updatedRoster: newRoster
},
success: function(response){
console.log(response);
if (response == 'success'){
alert('Successfully updated');
} else {
alert('Error');
}
}
});
// server
app.post('/students', function(req, res){
db.students.update(
{ "_id": req.body._id },
{ $set: { "name": req.body.updatedRoster } },
function(err, docs) {
if (err) throw err
res.send('success');
}
);
});
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);
});