How to findAll in mongoosejs? - mongodb

My code is like that:
SiteModel.find(
{},
function(docs) {
next(null, { data: docs });
}
);
but it never returns anything... but if I specify something in the {} then there is one record. so, how to findall?

Try this code to debug:
SiteModel.find({}, function(err, docs) {
if (!err) {
console.log(docs);
process.exit();
}
else {
throw err;
}
});

The 2017 Node 8.5 way
try {
const results = await SiteModel.find({});
console.log(results);
} catch (err) {
throw err;
}

From the documentation:
let result = SiteModel.find({}, function (err, docs) {});
or using async await you can do like this also:
let result = await SiteModel.find({});

const result = await SiteModel.find() - Without the {} in the .find() function works as well.

Related

how to get callback return value in nestjs

I am going to use vonage for text service.
However, only node.js syntax exists, and the corresponding API is being used.
There is a phenomenon that the callback is executed later when trying to receive the values ​​returned from the callback to check for an error.
How can I solve this part? The code is below.
await vonage.message.sendSms(from, to, text, async (err, responseData) => {
if (err) {
console.log('1');
result.message = err;
} else {
if (responseData.messages[0]['status'] === '0') {
console.log('2');
} else {
console.log('3');
result.error = `Message failed with error: ${responseData.messages[0]['error-text']}`;
}
}
});
console.log(result);
return result;
When an error occurs as a result of executing the above code,
result{error:undefined}
3
Outputs are in order.
From what I can understand the issue is that you are passing a async callback. you could simply just give vonage.message.sendSms() a synchronous callback like so.
const result = {};
vonage.message.sendSms(from, to, text, (err, responseData) => {
if (err) {
console.log('1');
result.message = err;
} else {
if (responseData.messages[0]['status'] === '0') {
console.log('2');
} else {
console.log('3');
result.error = `Message failed with error: ${responseData.messages[0]['error-text']}`;
}
}
});
if you want to use async or promises I would suggest something like this
const sendSMS = (from, to, text) => new Promise( (resolve, reject) => {
vonage.message.sendSms(from, to, text, (err, responseData) => {
if (err) {
reject(err);
} else {
resolve(responseData);
}
});
});
// elsewhere
sendSMS(from, to, text)
.then(...)
.catch(...);

Store collection value to variable

I am having issues storing a value in mongodb to a variable to use within my webpage.
When the user fills out a form on my website, I am trying to figure out what the arrivalTrailer was when the user filled out the arrival form.
So far I have
function previousLoad(loadNumber, callback){
CheckCall.find({loadNumber: loadNumber}).sort({date: 'desc'}).limit(1), function(err, arrival){
if (err){
callback(err, null);
}
else {
callback(null, arrival[0]);
}
}};
previousLoad(loadNumber, function(err, arrival){
if (err){
console.log(err);
}
else{
arrivalTrailer = arrival;
console.log(arrival);
}
});
console.log(previousLoad.arrival);
console.log(arrivalTrailer);
Both output as undefined when I try to console.log the variables.
Thank you :D
Try this :
async function previousLoad(loadNumber) {
try {
let resp = await CheckCall.find({ loadNumber: loadNumber }).sort({ date: -1 }).limit(1)
return resp[0]
} catch (error) {
console.log('error ::', error)
throw new Error (error)
}
}
/** You can return response from previousLoad but to test it, Call it from here */
previousLoad(loadNumber).then(resp => { console.log('successfully found ::', resp)}).catch(err => { console.log('Error in DB Op ::', err)});

Aws lambda supports mongoose middleware?

Does AWS lambda supports mongoose middleware, I'm using .pre() to check data exists on save.
here is my function call for save
res = new cModel();
res.pre('save', function (next) {
cModel.find({name: company.name}, function (err, docs) {
if (!docs.length){
next();
}else{
console.log('company name exists: ',company.name);
next(new Error("Company Name exists!"));
}
});
}) ;
this is my function call to update
company_model.companySchema.pre('update', function (next) {
try {
cModel.find({ name: { $regex: new RegExp(`^${this.getFilter().name}$` , 'i') }}, function (err, docs) {
try {
if (!docs.length) {
next();
} else {
console.log('company name exists: ', this.getFilter().name);
next(new Error("Company Name exists!"));
}
} catch (e) {
console.error('error in cModel.find: ' + e.message);
}
});
} catch (e) {
console.error('error in pre save : ' + e.message)
}
});
eInside a pre('save',... hook, the reference to the current document is found under this. Here I've replaced company with this in your example.
const schema = new mongoose.Schema({})
schema.pre('save', function (next) {
cModel.find({name: this.name}, function (err, docs) {
if (!docs.length){
next();
} else {
console.log('company name exists: ', this.name);
next(new Error("Company Name exists!"));
}
});
});
const cModel = mongoose.model("cmodel", schema)
This error doesn't have anything to do with lambda, except that the execution environment in lambda seems to be swallowing the error in the async method. To see the error being thrown, you can wrap the contents of your callback in a try {...} catch (e) {...} block and log the error in the catch block:
const schema = new mongoose.Schema({})
schema.pre('save', function (next) {
try {
cModel.find({name: this.name}, function (err, docs) {
try {
if (!docs.length){
next();
} else {
console.log('company name exists: ', this.name);
next(new Error("Company Name exists!"));
}
} catch (e) {
console.error('error in cModel.find: ' + e.message)
}
});
} catch (e) {
console.error('error in pre save : ' + e.message)
}
});
const cModel = mongoose.model("cmodel", schema)
Update
Using .pre('update'... will have this referencing the query, not the document, as the document is never loaded. You can access parts of the query using getFilter() and getUpdate().
Here is an example to check if company exists before making an update:
const schema = new mongoose.Schema({})
schema.pre('update', function (next) {
let newName = this.getUpdate().name;
cModel.find({name: newName }, function (err, docs) {
if (!docs.length){
next();
} else {
console.log('company name exists: ', newName);
next(new Error("Company Name exists!"));
}
});
});
const cModel = mongoose.model("cmodel", schema)

Waterline ORM assign the result of find to a variable

I want to combine the results of 2 queries and then return them as one, like this:
test: async (req, res) => {
const valOne = TableOne.find({ id: id })
.exec((err, result) => {
if (err) {
res.serverError(err);
}
return result;
});
const valTwo = TableTwo.find({ id: id })
.exec((err, result) => {
if (err) {
res.serverError(err);
}
return result;
});
const data = {
keyOne: valOne,
keyTwo: valTwo,
};
res.json(data);
}
I understand above code won't return because it's async. How can I achieve this?
There is not much info you supply: node version, sails version, etc.
There are several approaches here:
1. Using promises
2. Using callback chaining
3. Using await/async
If you use sails 1.0 and node >= 8, your best bet is to use await/async, so your code should work like that:
test: async (req, res) => {
let valOne, valTwo;
try {
valOne = await TableOne.find({ id: id });
valTwo = await TableTwo.find({ id: id });
} catch (err) {
return res.serverError(err); //or res.badRequest(err);
}
const data = {
keyOne: valOne,
keyTwo: valTwo,
};
res.json(data);
}

Using design documents in pouchDB with crypto-pouch

After testing pouchDB for my Ionic project, I tried to encrypt my data with crypto-pouch. But I have a problem with using design documents. I used the following code:
One of my design documents:
var allTypeOne = {
_id: '_design/all_TypeOne',
views: {
'alle_TypeOne': {
map: function (doc) {
if (doc.type === 'type_one') {
emit(doc._id);
}
}.toString()
}
}
};
For init my database:
function initDB() {
_db = new PouchDB('myDatabase', {adapter: 'websql'});
if (!_db.adapter) {
_db = new PouchDB('myDatabase');
}
return _db.crypto(password)
.then(function(){
return _db;
});
// add a design document
_db.put(allTypeOne).then(function (info) {
}).catch(function (err) {
}
}
To get all documents of type_one:
function getAllData {
if (!_data) {
return $q.when(_db.query('all_TypeOne', { include_docs: true}))
.then(function(docs) {
_data = docs.rows.map(function(row) {
return row.doc;
});
_db.changes({ live: true, since: 'now', include_docs: true})
.on('change', onDatabaseChange);
return _data;
});
} else {
return $q.when(_data);
}
}
This code works without using crypto-pouch well, but if I insert the _db.crypto(...) no data is shown in my list. Can anyone help me? Thanks in advance!
I'm guessing that your put is happening before the call to crypto has finished. Remember, javascript is asynchronous. So wait for the crypto call to finish before putting your design doc. And then use a callback to access your database after it's all finished. Something like the following:
function initDB(options) {
_db = new PouchDB('myDatabase', {adapter: 'websql'});
if (!_db.adapter) {
_db = new PouchDB('myDatabase');
}
_db.crypto(password)
.then(function(){
// add a design document
_db.put(allTypeOne).then(function (info) {
options.success(_db);
})
.catch(function (err) { console.error(err); options.error(err)})
.catch(function (err) { console.error(err); options.error(err);})
}
}
initDB({
success:function(db){
db.query....
}
)