MongoDB, Mongoose, and composite _id - node.js

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.

Related

Check stored value using mongoose

I’m looking for the fastest way to get all objectIDs of a collection with a privacy value 'public'.
In this image, privacy's value is 'public', so node should give me the '_id' of this object (in this example '57bc4b9f466fab7c099a3f94').
My attempt:
var mongoose = require('mongoose');
mongoose.connect('localhost:27017/databasename');
var Schema = mongoose.Schema;
var collectionsNameSchema = new Schema({
updated: {type: Date },
privacy: { type: Object }
}, {collection: 'spots'});
var collectionsNameData = mongoose.model('collectionsNameData', collectionsNameSchema);
...
collectionsNameData.find({privacy: 'public'})
From what i see you have a problem in query to mongoDB.
Try like this.
collectionsNameData.find({'privacy.value': 'public'});
This should return desired result.
You also may want to use projection as second parameter in find to return only fields that you want. Keep in mind that _id returned by default.
Hope this helps.

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'}}

Mongoose searching on array subdocument ObjectId not working

This is honestly driving me crazy. Here's the problem:
I'm running the following query in Mongoose:
s.findSubdocument=function(uid, cb)
{
this.model('User').find({"flwng._id":uid.toString()}).select('flwng').exec(cb);
}
on the following User Schema:
var userSchema= new mongoose.Schema(
{
uname:{type:String, index:{sparse:true, unique:true, dropDups:true}}, //the username
email:String,
pwd:{type:String},
flwng:[{_id : {type : mongoose.Schema.ObjectId},uname : String}], //_id of users I am following
flwrsz:Number,
flwngsz:Number,
feedsz:Number,
}, {j: 1});//j:1 means guarantee it is written to the journal.
userSchema.set('autoIndex', true);
userSchema.index({"fid":1}, {sparse:true, unique:true, dropDups:true});
userSchema.index({"flwng._id" : 1});
Where uid="53c4f16c431247694f0000a3" ==> but I get an empty array back :(
When I run the same exact query in the mongo shell:
db.users.find({"flwng._id":"53c4f16c431247694f0000a3"});
I get the right set of results back. I tried with and without an index and schema on "flwng._id", I tried to drop the index, reIndex and I'm now running out of ideas. Am I doing something wrong with Mongoose?
Any help would be appreciated - thanks!
Henri
There's a mismatch between your existing documents in mongodb and your schema. Your data has records where flwng._id is a String, which is why you get results in the mongo shell. But your mongoose schema defines that as an ObjectId, so when you query with mongoose, mongoose casts your string value to an ObjectId and the query doesn't match. Either write a migration to fix your existing data or update your schema to match your data in terms of String vs ObjectId data type and things should start working through mongoose.

CastError: Cast to ObjectId failed for value "" at path "_id"

Well, I see that here are a few posts like this, but they didn't help me ...
let me describe my problem:
I have two Schema's
var A = new Schema({
someAttribut: {type: String},
b: {type: ObjectId, ref:'B'}
});
var B = new Schema({
someAttribut2: {type: Boolean, 'default': false'}
});
Now I'm in the situation that I already have a B-Object and I want to create an A-Object.
So i do it this way:
var a = new A(req.aFromClient); // {_id:null, someAttribute:'123', b:null}
//load b from Database ...
a.b = existingBFromDatabase; // {_id: 'Sb~Õ5ÙÐDâb', someAttribute2: false}
The b object is loaded from my monogDB. The debugger shows me a valid ObjectId (53627ed535d9d04416e26218 or Sb~Õ5ÙÐDâb) for my b .
But when I save my new A-Object, i get the error: 'CastError: Cast to ObjectId failed for value "" at path "_id"'
I don't understand why I get this error.
Firstly, I don't define the id in the schema, so mongoose should add it, which seems to work.
Secondly, I think that mongoose should generate a new ID when I create an a object.
do you have any proposal?
Based on the comment in the code, _id does have a value (of null). So you need to remove _id from req.aFromClient before creating your new A doc from it:
delete req.aFromClient._id;
var a = new A(req.aFromClient);
You should do:
a.b = existingBFromDatabase._id;
Because mongoose only works with the id of the already existing object.

Not able to remove document from mongo in Node

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) }, ...)

Resources