var query = { "to": req.params.id };
var mysort = { receivedDate: 1 };
Message.find(query, (err, doc) => {
if (!err) {
res.json(doc);
} else {
res.json(err);
}
});
The syntax is like the following:
db.collecttionName.find().sort({date:1});
But instead of date, you can pass in other criteria.
Related
When I run the script, the error returns.
TypeError: db.collection is not a function
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://abc:12345**#xxxx.mlab.com:&&&&/myDB";
MongoClient.connect(url, function(err, db) {
if(err) {
console.log(err);
} else {
console.log("Database created!");
db.collection('users').aggregate([{
'$match': {
'organization.organizationId': "e1716c62-fdce-11e7-8be5-
0ed5f89f718b"
}
},{
"$project": {
"deviceDetails": 1,
"userDetails": 1
}
}], function(error, documents) {
if (error) {
console(error);
} else {
console.log(documents);
}
});
});
Hi, could you please help me where am I doing wrong.Thanks!
With Mongo Driver 3.0 or above, the connect callback returns err and client instead of db. To get the db out of the client do this,
var db = client.db;
In your case, it will look something like this,
MongoClient.connect(url, function(err, client) {
if(err) {
console.log(err);
} else {
var db = client.db;
console.log("Database created!");
db.collection('users').aggregate(...)
}
})
Use MongoClient.connect(url, function(err, client)) where this was released in recent updates. For more info refer Mongo Driver Docs.
var MongoClient = require('mongodb').MongoClient;
// Dont use database name in link
var url = "mongodb://abc:12345**#xxxx.mlab.com:&&&&";
MongoClient.connect(url, function(err, client) {
if (err) {
console.log(err);
} else {
let db = client.db('myDB')
console.log("Database created!");
db.collection('users').aggregate([{
'$match': {
'organization.organizationId': "e1716c62-fdce-11e7-8be5-0e d5f89f718b "
}
}, {
"$project": {
"deviceDetails": 1,
"userDetails": 1
}
}], function(error, documents) {
if (error) {
console(error);
} else {
console.log(documents);
}
});
}
});
First you should check that database connect or not only run this code so that this confirm that variable url is correct or mongodb is correctly installed.
MongoClient.connect(url, function (err, db) {
if (err)
{
console.log("Failed connecting to the database. " + err);
}
else
{
console.log(Sucessfully)
}
});
Been banging my head in the wall on this, so any help would be greatly appreciated. With MongooseJS, I'm doing a Model.find and then looping through those results and doing a findAndUpdate.
(basically, get list of URLS from MongooseJS, "ping" each URL to get a status, then update the DB with the status).
Schema
var serverSchema = new Schema({
github_id: { type: String, required: true },
url: { type: String, required: true },
check_interval: Number,
last_check: {
response_code: Number,
message: String,
time: Date
},
created_at: Date,
updated_at: Date
})
Here's a code snippet:
// Doesn't work
Server.find(function (err, items) {
if (err) return console.log(err)
items.forEach(function (item) {
var query = {url: item.url}
Server.findOneAndUpdate(query, {updated_at: Date.now()}, function (err, doc) {
if (err) return console.log(err)
console.log(doc)
})
})
})
// Works!
var query = {url: 'https://google.com'}
Server.findOneAndUpdate(query, {updated_at: Date.now()}, function (err, doc) {
if (err) return console.log(err)
console.log(doc)
})
With debugging on, I can see that the .find() is getting the data I want. However, it seems that he findOneAndUpdate within the .find() never runs (item.url is set correctly) and I don't get any errors, it just doesn't run.
Any help would be GREATLY appreciated.
You can achieve that without find and then update you can do this in only one update operation
Server.update({}, { $set: { updated_at: Date.now() } }, function(err, doc) {
if (err) return console.log(err) {
console.log(doc)
}
})
In case you need to loop on items for specific reason to handle urls then try the code below
var Server = require('../models/server');
Server.find(function(err, items) {
if (err) {
return console.log(err)
} else {
items.forEach(function(item) {
var query = { url: item.url }
Server.update(query, { $set: { updated_at: Date.now() } }, function(err, doc) {
if (err) return console.log(err)
console.log(doc)
})
})
}
})
Mongodb Connection:
var secrets = require('./secrets');
var mongoose = require('mongoose');
module.exports = function() {
var connect = function() {
var mongoLink = "";
if (process.env.NODE_ENV === 'production') {
mongoLink = secrets.db.prod;
} else {
mongoLink = secrets.db.dev;
}
mongoose.connect(mongoLink, function(err, res) {
if (err) {
console.log('Error connecting to: ' + mongoLink + '. ' + err);
} else {
console.log('Connected to: ' + mongoLink);
}
});
};
connect();
mongoose.connection.on('error', console.log);
mongoose.connection.on('disconnected', connect);
}
I want to query a user by id, and then bring only the the foods that match to a type, how can i do this?
var type = 'fish';
var id = '597a348286ffe50d882a3033';
User.findById(id, { 'food.type': type }, 'food', function(err, model) {
if (err) {
console.log(err);
}
if (!model) {
console.log('no model');
}
if (model) {
console.log(model);
}
});
I would use aggregate combined with $filter:
User.aggregate([{
$match: { '_id': ObjectId('597a348286ffe50d882a3033') }
}, {
$project:
{
food: {
$filter: {
input: '$food',
as: 'food',
cond: {
$eq: ['$$food.type', type]
}
}
}
}
}])
This will first select the document matching the given Id then will return the list of foods of the given type.
Just filter the food after you get the user.
User.findById(id, function (err, user) {
if (err) {
console.log(err);
}
if (!user) {
console.log('no user');
}
if (user) {
var food = user.food.filter(function (food) { return food.type === type; });
}
});
You can create an obj something like this
var obj =
{
_id:'597a348286ffe50d882a3033',
'food.type' : 'fish'
}
and then pass this function as filter
User.find(obj, function(err, model) {
if (err) {
console.log(err);
}
// find will return empty array and not null
if (!model.length) {
console.log('no model');
}
if (model) {
console.log(model);
}
});
If you are finding the object using mongo _id field you don't have to use additional filter function after query execution you directly specify in the search query
Model.findOne({_id: '123jasdoisd123', 'food.type': type },
function(err, food){
if(err) return err;
if(!food){
// send the empty data
return []
}
return food;
}
)
I've Googled around and can't find any solid information on how to ignore duplicate errors when using bulk insert.
Here's the code I'm currently using:
MongoClient.connect(mongoURL, function(err, db) {
if(err) console.err(err)
let col = db.collection('user_ids')
let batch = col.initializeUnorderedBulkOp()
ids.forEach(function(id) {
batch.insert({ userid: id, used: false, group: argv.groupID })
})
batch.execute(function(err, result) {
if(err) {
console.error(new Error(err))
db.close()
}
// Do some work
db.close()
})
})
Is it possible? I've tried adding {continueOnError: true, safe: true} to bulk.insert(...) but that didn't work.
Any ideas?
An alternative is to use bulk.find().upsert().replaceOne() instead:
MongoClient.connect(mongoURL, function(err, db) {
if(err) console.err(err)
let col = db.collection('user_ids')
let batch = col.initializeUnorderedBulkOp()
ids.forEach(function(id) {
batch.find({ userid: id }).upsert().replaceOne({
userid: id,
used: false,
group: argv.groupID
});
});
batch.execute(function(err, result) {
if(err) {
console.error(new Error(err))
db.close()
}
// Do some work
db.close()
});
});
With the above, if a document matches the query { userid: id } it will be replaced with the new document, otherwise it will be created hence there are No duplicate key errors thrown.
For MongoDB server versions 3.2+, use bulkWrite as:
MongoClient.connect(mongoURL, function(err, db) {
if(err) console.err(err)
let col = db.collection('user_ids')
let ops = []
let counter = 0
ids.forEach(function(id) {
ops.push({
"replaceOne": {
"filter": { "userid": id },
"replacement": {
userid: id,
used: false,
group: argv.groupID
},
"upsert": true
}
})
counter++
if (counter % 500 === 0) {
col.bulkWrite(ops, function(err, r) {
// do something with result
db.close()
})
ops = []
}
})
if (counter % 500 !== 0) {
col.bulkWrite(ops, function(err, r) {
// do something with result
db.close()
}
}
})
I am building a JSON API with ExpressJS, NodeJS and Mongoose:
Input -> id:
app.get('/folder/:id', function (req, res){
return Cars.find({reference: req.params.id}, function (err, product) {
if (!err) {
console.log(product);
return res.send(product);
} else {
return console.log(err);
}
});
});
It shows well the JSON:
[{"_id":"B443U433","date":"2014-08-12","reference":"azerty","file":"087601.png","
....:.
{"_id":"HGF6789","date":"2013-09-11","reference":"azerty","file":"5678.pnf","
...
I just want to display the _id in the JSON, so it is good when I have lots of data.
How I can do that? Something like a filter?
You can chain calls to select and lean to retrieve just the fields you want from the docs you're querying:
app.get('/folder/:id', function (req, res){
return Cars.find({reference: req.params.id}).select('_id').lean().exec(
function (err, product) {
if (!err) {
console.log(product);
return res.send(product);
} else {
return console.log(err);
}
});
});
You would have to iterate over your "products" object to obtain the ids
Something like this:
(Disclaimer: I haven't tested this)
app.get('/folder/:id', function (req, res){
return Cars.find({reference: req.params.id}, function (err, product) {
if (!err) {
console.log(product);
var ids = new Array();
for(var i = 0; i < product.length; i++){
ids.push(product[i]._id);
}
return res.send(JSON.stringify(ids));
} else {
return console.log(err);
}
});
});
--Edit
Also, "products" may already be a JSON string. You may want to parse it before looping.
product = JSON.parse(product);
Other answers are true but I think it's better to limit data in mongoose like this :(it's same as mongo shell commands)
app.get('/folder/:id', function (req, res){
Cars.find({reference: req.params.id} ,{ _id : true } ,function (err, product) {
if (!err) {
console.log(product);
} else {
console.log(err);
}
});
});