node-mongodb-native remove by DBRef $id (dot issue) - node.js

I have 2 collections in my mongodb database: users and posts.
And in posts collection I have DBRef field like this:
user : DBRef('users', ObjectId('...'), null)
When I'm going to remove some post by user id, I do the following:
db.posts.remove({ 'user.$id' : ObjectId('...') })
And it works great, but not from node-mongodb-native. From node-mongodb-native I'm getting following error while doing this request:
key must not contain '.'
Can anyoune see that? Thank you for your help and explanations if I'm wrong in something.
Update
find requests by DBRef $id work fine!
Node.js code:
var mongodb = require('mongodb')
, nconf = require('nconf')
, MongoClient = mongodb.MongoClient;
MongoClient.connect(nconf.get('db:connectionString'), function(mongoConnectionError, db) {
if (mongoConnectionError) throw mongoConnectionError;
db
.collection('posts')
.remove({ 'user.$id' : new mongodb.ObjectID('...') }, {}, function(err, removedItems) {
if (err) { throw err; }
console.log('Removed items: ' + removedItems);
});
});

I've used a similar model, but my post was from ONE user, making it simply:
db.posts.remove({'user_id' : ObjectID('...') });
In this case, it looks more like the collection posts has an array user with id in it.
If I'm not mistaken, you should use the $ in the user array to do something to an element in an array once you've matched.
If your purpose is removing the entire post, simply remove it by matching the id in the users array:
db.posts.remove({user:{$in:ObjectID('...'}});
Otherwise, $pull, as said above.

Related

How to get all keys + in a collection + mongodb +mongoose

I want to get all distinct keys from a collections in mongoDB.
I refereed the following links:
Get names of all keys in the collection
Querying for a list of all distinct fields in MongoDB collection and etc.
But still i didn't get the right solution...
As i am using mongoose in the first link reference syas runCommand is not a function.
As findOne() will give the first document keys alone but i need all distnct keys
userModel.findOne(condition, projection, callback)
Please share your ideas..
If you are using Mongoose 3.x, then you can try this :
userModel.find().distinct('_id', function(error, ids) {
// ids is an array of all ObjectIds
});
Or you can find all the documents and extract key from that like :
var keys = {};
var docKeys = [];
userModel.find({}, function(err, allDocs){
allDocs.forEach(function(doc){
docKeys = Object.keys(doc);
docKeys.forEach(function(docKey){
if(!keys[docKey]) keys[docKey] = true;
})
})
})
I have just written for getting logic, you can change according to your requirements and efficiency
Try like this you will get all of your keys defined into your mongoose model/Schema.
import Model from 'your_model_path'
for(let property in Model.schema.obj){
console.log("key=====>",property);
}

How to get join result using mongoose populate, match (2 collections)

User Schema
var UsersSchema = new Schema({
username:String,
city:String
},{collection:'User'});
//sample data {'username':'7700010000',city:'mumbai'}
College Schema
var College = new Schema({
college:String,
user_sess:[type:String,ref:"User"]},{collection:'College'});
//sample data {'college':'adarsh college','user_sess':'Sess$7700010000'}
I am trying to get result from college collection based on user_sess. but problem is user_sess has value with prefix value 'Sess$'
so user_sess = prefix + username from collection User
var prefix = 'Sess$';
College
.find({ "user_sess": prefix + req.body.user_id})
.populate({'user_sess'})
.exec(function (err, users) {
console.log();
if (err)
res.send(err);
res.json(users);
});
If there is a match for user_sess then result should look like
{'college':'adarsh college','username':'7700010000','city':'mumbai'}
I already solved it by adding reference keys in my respective collection because I i tried regex but it added extra latency in my responses. We are using parse server framework but we want to get rid of it but since parse saves data differently I was not able to do joins using mongoose schema.
Thank you.

findOne not returning correct result( Mongo DB and nodejs)

I have stored a document in collection and when i am trying to retrieve it via findOne, it is returning me wrong result:
My Mongoose model is like:
var db = require('../db');
var mongoose = db.mongoose_var;
var companySchema = mongoose.Schema({
companyName:String
});
module.exports = mongoose.model('Company',companySchema);
Which then i am using in my server.js as :
var CompanySchema = require('./schemas/companySchema');
and when I am trying to find already inserted record as following:
CompanySchema.findOne({'Company.companyName':jsonObj.companyName},function(err,companyName){
console.log('companyName foudn:'+companyName);
if(companyName !== null){
res.status(404).json({status:'Name already in the DB'});
return;
}else{...
Its unable to find this record, but its returning probably the first record.
Folloing record is present in thedb:
When I am trying to add another company and using this findOne to check if this name already exists, findOne returns this record only. My log snippets
whereas mongo shell returns proper result only.
In mongo shell, I am using " " around field and values, not in findOne Api.
Thanks in Advance
You should probably use the following :
CompanySchema.findOne({'companyName':jsonObj.companyName},function(err,companyDocument){
if(err) console.log(err);
console.log('company found:' + companyDocument);
if(companyDocument){
res.status(404).json({status:'Name already in the DB'});
return;
}else{...
The mistake in your code was that you were using Company.companyName instead of companyName. companyName is the name of the field in the Company collection.
Hope this helps you.

Is there a way to list collections with mongoskin?

I already have an established database connection. I need to list the names of the collections in the database. Is it possible?
db.collectionNames(function(err, collectionArrayResult) {
//Now do something with collectionArrayResult
});
The result is an array of objects with a 'name' property, like this:
[
{ name: '<dbName>.<collectionName>' },
...
]
Careful though - <dbName>.system.indexes will be returned too.
To show collections into database from mongo shell :
db.getCollectionNames()
So to show collection in mongoskin try that
var collections = db.collections();
collections.each(function(err, collection) {
console.log(collection);
});
according to this link Mongoskin Tutorial

Query Return Collection From MongoDb Mongoose in Node

Is it possible to query a returned collection in mongoose for mongodb. So in the example below I wish to return to the page the full list of steps, as well as the currentStep. The line I am unsure about is currentStep: steps.?????(page).
Thanks
var page = (req.params.page == undefined?1:req.params.page)
db.stepModel.find().sort({number:1}).exec(function(err, steps) {
if (err) { return next(err); }
res.render('scheme', {
title: 'Fnol',
user: req.user,
steps:steps,
currentStep: steps.?????(page),
page:page
});
};
You can use steps as an array:
currentStep : steps[page - 1].toObject()
The - 1 is because it seems that you use 1-based indexing for the page, whereas arrays are 0-based.
The toObject() converts the Mongoose result into a proper JS object, so you can access properties like _id from within your template.

Resources