CastError: Cast to ObjectId failed for value "" at path "_id" - node.js

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.

Related

How to convert string to mongoose.Types.ObjectId in mongoose

I just add a field like this in modelSchema
receiverId:[{ type : Schema.Types.ObjectId, ref: 'UserChat' }]
In controller:
var recievedIds = [];
recievedId = new mongoose.Types.ObjectId(recievedId);
recievedIds.push(recievedId);
console.log(typeof recievedId);
messageInfo.receiverId = recieverIds;
new UserChat(messageInfo).save().then((info)=>{
res.send(info);
}).catch((infoError) =>{
res.send('FAILED_TO_SEND_MESSAGE');
});
It is giving type as object not as ObjectId
and also it is pushing empty array into mongodb
i tried removing new infront of mongoose in the above object creation
Can anybody help me how to create a ObjectId?
As the doc states: An ObjectId must be a single string of 12 bytes or a string of 24 hex characters.
Please verify that your receiverId meets that requirement.

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.

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.

Adding field in Mongoose plugin gives "TypeError: Invalid value for schema path `CreatedBy.type`"

I'm trying to make a CreatedBy Mongoose plugin, but when trying to use the ObjectId as the field type it gives me ("account" is another defined collection already):
TypeError: Invalid value for schema path `CreatedBy.type`
& here is the plugin code:
mongoose = require 'mongoose'
module.exports = exports = updatedByPlugin = (schema, options) ->
schema.add CreatedBy:
type: mongoose.Schema.Types.ObjectId
ref: "account"
schema.pre "save", (next) ->
#CreatedBy = options.accountId
next()
return
schema.path("CreatedBy").index options.index if options and options.index
return
So how I can modify the ref value to make it work?
Well, you won't believe it, but I solved it by adding the CreatedBy field this way
schema.add CreatedBy:
ref: "account"
type: mongoose.Schema.Types.ObjectId
Yes, by just exchanging the 2 lines for ref & type!! . It is weird how exchanging these 2 lines could break the code :| !!!

Mongoose: Find reference documents by id before inserting a doc

Is there a way for checking if a reference document id exists in the array field of its "parent" model?
Imagine you know the objectId you want to check if exists because you don't want duplicates and also want to avoid that an error was thrown when trying to insert it.
I would like to know if there is an elegant and simple way as the method mongoose provides when working with subdocuments: var doc = car._components.id(theComponentIdIWantToCheck)
In this case it is a reference document:
Example:
// Car.js
var CarSchema = new Schema({
name: String,
description: String,
_components: [ { type: Schema.Types.ObjectId, ref: 'Component'},]
});

Resources