Not able to remove document from mongo in Node - node.js

I'm trying to remove a document from a mongo database using Node. Is something wrong with my .remove method here:
deleteApplicant : function(req,res){
applicationModel.remove({_id:req.params.id} , function(err,count){
res.redirect('/applicants');
console.log(count)
})
}
Am I using the correct syntax?

_id in the database is probably of type ObjectId, but you're passing a string to the query.
Try this instead:
var ObjectId = require('mongodb').ObjectID;
...
applicationModel.remove({ _id : ObjectId(req.params.id) }, ...)

Related

How to exclude _id property from MongoDB Atlas query with NodeJS Express application

I cannot omit my _id field when I go to retrieve my documents from a MongoDB Atlas collection.
const cursor = await client.db("databaseName").collection("collectionName").find();
The second parameter in the find() is the project list.
The catch here is that whenever you project data, _id is never removed by default. To remove _id you need explicitly exclude it like this:
const cursor = await client.db("databaseName").collection("collectionName").find({name: ""}, {_id: 0});
-> find() documentation reference here
-> projection details here
This ended up working for me.
const cursor = await client.db("databaseName").collection("collectionName").find({},{ projection: { _id: 0}});

Insert document with nested ObjectId

I am trying to insert a document into my mongodb that looks like this:
_id : ObjectId(<id>)
players : {
ObjectId(<id>) {
entry : 'foo'
}
}
However, I can't form JSON in node with an ObjectId as a key. What's the best practice for this? Thanks!
According to the MongoDB documentation:
Field names are strings.
So you can't use ObjectId's as keys, but you can use their string representation:
var playersObj = {};
playersObj[ObjectId()] = { entry : 'foo' }; // this will stringify the ObjectId
var document = {
_id : ObjectId(),
players : playersObj
};

MongoDB, Mongoose, and composite _id

New to Mongodb & Mongoose.js.
I have created the following schema & model:
var schema = new Schema({
_id: {part1: String, part2: Number},
name: String
});
mongoose.model('myDoc', schema);
I can save this, and when I view it on the mongo command line, it looks fine.
However in mongoose when I do:
myDoc.find({}, function(err, recs) {
var rec = recs[0];
console.log('----' + JSON.stringify(rec));
});
I get my object printed out, but with the following exception: Cast to ObjectId failed for value "[object Object]" at path "_id"
I've seen a few explanations, but I don't understand what I'm doing wrong, and how I need to fix it.
According to mongodb documentation the _id can be bson-type. What am I doing wrong? Isn't {part1: String, part2: Number} a bson?
According to this post from the Mongoose author, compound _id fields aren't yet supported by Mongoose.

Mongoose nodejs find not working correctly

so I'm doing a mongoose find and I've defined collections etc and it all works fine EXCEPT when I try to do a find by a value.
var searchID = req.user.id;
console.log(searchID);
Locations.find({userid: '541f69e7fd4c3b07108c92c0'}, function(err, location) {
if (err) return console.error(err);
console.log(location);
});
the userid is a property which is the ID of the user that created it. The find doesnt work in mongo console either.
Any ideas? I can do finds by the actual _id of the location or any other value.
As Neil Lunn commented, your problem is almost certainly your schema not being correct. Once your mongoose schema clearly defines the userid property as being of type mongoose.Schema.Types.ObjectId, mongoose will start casting your string value from the query to a proper ObjectId instance before sending it to mongodb, and thus the query will start matching documents and you'll see results.
{userid: {type: mongoose.Schema.Types.ObjectId, ref: 'Users'}}

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

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.

Resources