The basic idea is something like this:
model.find({}, function(err, docs) {
docs.forEach(function(doc) {
// update it with whatever new object
model.update({"category":"cat1"});
});
});
Now my question is any sort of update/save doesn't work. I can find, count, etc with the model. I've tried doc.save(), model.findOneAndUpdate(), using the $set parameter for particular fields, they don't work. I went to mongo shell and typed the update command with the parameter, it worked.
One time it did work, was when I tried to put new documents using var m = new model({..}) and m.save() from outside the callback function of find(). But I need to find documents by their fields, and update those.
I feel like I'm missing something really elementary, could someone help me out?
edit: mongoose.disconnect() was being called later on in the code. So query did not execute.
Another possibility cause to this problem is when you use Mixed types, as in Schema.Types.Mixed. If you only update the Mixed field, then Mongoose doesn't know you've updated that field. So you need to call markModified
I ran into this recently and it was a pain in the neck to find out what was going on.
Unless it's just a typo, you're doing an update on the wrong object. You probably want to do
model.find({}, function(err, docs) {
docs.forEach(function(doc) {
doc.update({/fields here/});
});
});
Above answer is incorrect.
Edit
After thinking a little about it, why are you doing find at all? You should be able to update your docoments without it. Check the API docs for update
model.update({}, {field1: 'updated value'}, function(err) {});
Related
I can use KNEX=debug:query npm start so I get logs and time how long queries took.
I would like to know where these queries are defined (function name or file:line). Due to knexjs beeing ORM I can't find it in code easily.
I've usually have done it like this:
orm.on("query", (q) => try { throw new Error() }catch(e){ console.log(query, e.stack) }
First question - why it's not built-in for debugging? Or maybe it is? Second - how can I achieve this?
I'm working on an assignment to list all of the data in a mongoDB database, and am having trouble finding where I'm going wrong. It seems like a fairly simple problem, but whenever I run the provided mocha test, it keeps throwing 404 errors. Here is the relevant portion of the test:
it('should it able to retrieve all listings', function(done) {
agent.get('/api/listings')
.expect(200)
.end(function(err, res) {
should.not.exist(err);
should.exist(res);
res.body.should.have.length(147);
done();
});
});
And here is my code for the GET request. I've tried a few different ways of coding it, but this is seems like the simplest/most direct way to return the desired data as JSON.
exports.list = function(req, res) {
Listing.find(function(err, listing){
if(err){
res.status(404).send(err);
} else {
res.json(listing);
}})
};
Is there anything else I should be doing? I've been looking at tutorials and basic examples of requests and it seems like it should work, but it doesn't. Any help would be greatly appreciated.
Make sure that the middleware function (the code for GET request) is mapped to /api/listings
I'm not sure about exports.list. It should probably be module.exports
I'm assuming, based on ur code, that ur using the mongoose ODM. In which case, I think you need to pass a query to the find method check this out
You might wanna make sure that you're connected to the database at the time of test initialization and that that completes before the test starts
It always helps to log errors
Checkout express-generator to scaffold a boilerplate express app. Might help to compare it with your app, to check if it's wired correctly
Seems like you are not passing the first parameter to the find method. Only the callback ... try this:
Listing.find({}, function(err, listing) {
if (err) {
res.status(404).send(err);
} else {
res.json(listing);
}
})
I am assuming you want all records which is why we pass an empty object {}.
I'm trying to do a simple command line database transformation with node.js and sequelize. I've simplified my errant code down to the following, but it never returns:
// Set up database connection and models
var models = require('../models_sequelize');
models.User.findOne()
.then(a => {
console.log(a.name);
});
I get a name printed, but then the script hangs. What is wrong? How do I debug this to see what's stuck? I get the impression that there's an orphan promise that's not being fulfilled, but I don't understand where or why. I must be missing something obvious.
If I run the same interactively from the node console, it returns fine.
Sirko's comment re: close() gave me something to go on. I can stop the hanging with the following code:
var models = require('../models_sequelize');
models.User.findOne()
.then(a => {
console.log(a.name);
models.sequelize.close();
})
Alternatively, this seems to work too as I guess it's doing exactly the same thing:
var models = require('../models_sequelize');
models.User.findOne()
.then(a => {
console.log(a.name);
})
.finally(() => {
models.sequelize.close();
});
I also found something about connection pooling timeouts, but I don't think that affects my simple use case. I imagine it'll come into play in more complicated examples.
Would still like to find a good reference as to why this is necessary rather than just my guess.
I need to generate slug every time that post get saved into database. Specifficallly on Post.create and post.save. The single place where I may need this in PostShema.pre('validate') middleware like the following:
PostSchema.pre('validate', function (next) {
this.slug = sluglify(this.title);
return next();
});
All works fine except the fact that it happens in validate middlweare that should only check but not set.
SO my questuin is where should I reside my code for sluglify my title on creating or updating post?
This is not happening in the validation but before the validation. IMHO, it 's like if you are prepearing/cleaning your object before validating it; which is OK.
If you feel more confortable with that you could include it in a pre-save or pre-init instead of the pre-validate
I have follow the directions in mongoose here
PostSchema.pre('update', function() {
console.log('pre update');
console.log(this);
});
it is not firing this middleware. Am I missing something here?
I have added next so it looks exactly like my pre save, however that still does nothing.
Make sure you don't define this after mongoose.model() has been called. Please also take note that findOneAndUpdate / upserts or updates won't trigger this hook. Another reason why it wouldn't execute is that validation fails. Therefore you would need to setup a pre('validate') hoke
I think you have to add the await keyword before your promise.