I may be misunderstanding something, but on the client I have a request sent to the server. Something like:
$.post("/resources/remove", {"id": 52024e25b26d39f931000003})
On the server I have
Resource.remove({_id: request.body.id})
The "ID" is correct and using Resource.find with the same arguments returns the record I want to remove. However, when this is run it removes all Resource records. The return value of exec(function (err, returnValue) is the number of Resource records that were there, so it is definitely removing all of them. Using Remove.(request.body.id) does the same thing.
Do I need to do anything else to make sure that only the record with the corresponding _id is removed? If the entry is invalid why is it removing all records?
Try using Resource.findOneAndRemove Reference
I've never used that but this is what I use and it works perfectly for me
PostModel.findOne({_id: id}, function (err, result) {
if (err) {
throw err;
}
if (result) {
PostModel.remove({_id: id}, function (err, result) {
if (err) {
throw err;
}
res.json(200, result);
});
}
});
Related
function randomSpam(){
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
const dbo = db.db("database0");
dbo.collection("spams").aggregate([{ $sample: { size:1, } }]).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
}
Console output
As you can see above I managed to get a random document, now my question is : How can I access a field of the random document I have got? Thanks. (in this case the field named "link, check console output)
result[0].link
is what you want — the 0 refers to the first document, and the link refers to the field.
You can try, it should work:
result[0].link
I want to iterate insert to db. Right after the iteration is done, I want to generate success message and redirect user to the specific page. That's why I use async package.
Here's my code:
async.forEachOf(venue_1_split, function (venue, key, callback) {
pool.query("INSERT INTO peminjaman_venue VALUES (?,?,?,?,?,?,?)",
[id_event, venue, id_google_calendar, waktu_mulai_1, waktu_selesai_1, tanggal_peminjaman_1, tanggal_peminjaman_1],
function(err, rows, fields){
if (err) throw err;
});
req.flash('message_success', 'Berhasil mengajukan event');
callback(res.redirect('/pengajuan_event'));
}, function (err) {
if (err) console.error(err.message);
});
It works but seems to be not correct. First, it returns error `
"Can't set headers after they are sent"
And when i checked my db it only inserted 2 rows. The loop stopped on 2nd iteration. Can you fix my code. Thank you.
`
You are redirecting to /pengajuan_event after every insert. Try following code.
async.forEachOf(venue_1_split,
function (venue, key, callback) {
pool.query("INSERT INTO peminjaman_venue VALUES (?,?,?,?,?,?,?)",
[
id_event,
venue,
id_google_calendar,
waktu_mulai_1,
waktu_selesai_1,
tanggal_peminjaman_1,
tanggal_peminjaman_1
],
callback(err, rows, fields)
)}, function (err) {
if(err) {
console.error(err.message);
} else {
req.flash('message_success', 'Berhasil mengajukan event');
res.redirect('/pengajuan_event')
}
}
);
First off, don't worry, it's a tiny data set - I realise it wouldn't be wise to dump an entire production DB to a single screen via an API... I just need to get a JSON dump of entire (small) DB to return via an API endpoint in a Node.js application.
My application does successfully return single records with this code:
MongoClient.connect("mongodb://localhost:27017/search", function (err, db) {
if(err) throw err;
db.collection('results', function(err, collection) {
// search for match that "begins with" searchterm
collection.findOne({'string':new RegExp('^' + searchterm, 'i')}, function(err, items){
// get result
var result;
if (items == null || items.result == null){
result = "";
}
else {
result = items.result;
}
// return result
res.send(result);
});
});
});
So I know Node is talking to Mongo successfully, but how can I tweak this query/code to basically return what you get when you execute the following on the MongoDB command line:
$ db.results.find()
This is snippet.
model.find({}).exec(function (err, result) {
if (err) {console.error(err); return;}
else return result;
});
First use your predefined model and call find. the logic is to place a empty object {} essentially rendering . select all from this model.
Make sense?
Exactly as you've described it.
collection.find({}).exec((err, result) => {
if (err) {
console.log(err);
return;
}
if (result.length > 0) {
// We check that the length is > 0 because using .find() will always
// return an array, even an empty one. So just checking if it exists
// will yield a false positive
res.send(result);
// Could also just use `return result;`
});
Thanks guys, I appreciate your answers pointing me in the right direction, in terms of using {} as the query. Here is the code that eventually worked for me:
db.collection('results', function(err, collection) {
collection.find({}).toArray(function(err, docs) {
res.send(docs);
});
});
The crucial element being the toArray(...) part.
User.find().exec(function (err, users) {
if (err){
callback(err);
} else {
callback(users);
}
});
User.find(function (err, users) {
if (err) {
callback (err);
} else {
callback(users);
}
});
What is the benefit of using the top code? both seem to work equally well
They are identical and there's no benefit in your example
When you do not pass a callback to find function it won't execute but instead returns a query then you need to use exec()
var query = User.find();
now you can add some more criteria
query.where({age: 15});
and some more
query.select({name:1}); // or {firstname:1, lastname:1} etc.
now you've built up your query so to get the results you need to execute it.
query.exec(function(err, users){
});
But you can also do this like
User.find({age:15}, {name:1}, function(err, users){
});
Above is identical to
User.find({age:15}, {name:1}).exec(function(err, users){
});
since there's no callback in find function it will return query which means no results, exec will give you the results
I see often the following code snippet:
collection.insert({"some": "data"}, function (err, inserted) {
if (err) { /* do something */ return; }
if (!inserted || !inserted.length) {
console.error("Nothing inserted ...");
return;
}
/* do something */
});
Is the second if really required?
When the insert method doesn't send an err in callback and inserted variable is undefined, null or something like this?
The second argument passed to the callback of insert can be null (with err being null as well), according to the sources, when you're using MongoDB 2.6 (or higher), the write concern is 0 and there's a callback function passed.
I'm not running 2.6, so can't test this myself:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/demo?w=0', function(err, db) {
db.collection('test').insert({ foo : 'bar' }, function(err, inserted) {
console.log('I', inserted);
});
});
However, inserted would not be an array in this situation, but plain null. So the check would have to be if (! inserted) { ... }, and it wouldn't be an error (setting the write concern to 0 means you're just not interested in knowing if the insert failed or not).
We don't need second if for insert() callback. But we may need second if for update() callback.
I think the author of that code confused insert() with update() (?)
Insert document link
collection.insert({"some": "data"}, {safe: true}, function(err, records){
if (err) throw err;
console.log(records);
});
Side note: According to document, we must pass {safe: true} to get the err param in callback, because it is default to false. But I feel like it is true by default for me (including production mode)
Update document link
collection.update({"some": "data"}, function (err, count) {
if(err) throw err;
// SECOND IF
if(!count) {
console.log('NOTHING UPDATED');
}
});