I am using mongoose.
My schema is like
var tblTypes = new Schema({
_id: { type: String, required: true }
, desc: String
, priority: Number
}, { collection: 'tblTypes' });
while fetching records in the query i am giving like dis as query in findone
JSON
{ _id: "SFK" }
Its giving
{ message: 'Cast to ObjectId failed for value "CONFIRM" at path "_id"',
name: 'CastError',
type: 'ObjectId',
value: 'CONFIRM',
path: '_id' }
as error. Earlier its working in different system.
I am not sure about both the versions.
Where i am going wrong ?
Related
I am building an e-commerce web application with NodeJS with express and MongoDB. I working on an API for storing a product id and quantity in an array that is the user's cart.
This is the user model:
const userSchema = mongoose.Schema({
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
username: {
type: String,
required: true
},
access_level: {
type: Number,
default: 1
},
cart: {
type: [cartProductSchema],
default: []
}
})
This is the model for cartProductSchema:
const cartProductSchema = new mongoose.Schema({
product_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
},
quantity: {
type: Number,
required: true,
validate: { validator: Number.isInteger }
}
}, { _id: false })
This is the model for the Product:
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
stock: {
type: Number,
required: true,
validate: { validator: Number.isInteger }
}
}, {timestamps: true})
Here is the snippet of the router where the error is.:
// Add product to user's cart
const product = await Product.findOne({_id: req.body.product_id})
if (!product) {
return res.status(http.statusNotFound).json({
errors: [{ msg: "Invalid product id" }]
})
}
let cart = user.cart.slice()
cart.push({ product_id: product._id, quantity: req.body.quantity })
user.cart = cart // this is the line that causes the error
await user.save()
res.json({ msg: "Product added to cart" })
I am getting an error when I try to push a JSON object with product_id and quantity into a user's cart. There is a circular reference in the JSON object that's causing it, but I can't figure out what I did wrong. The error stack trace doesn't really Here is the error I get:
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
| property '__parentArray' -> object with constructor 'Array'
--- index 0 closes the circle
at stringify (<anonymous>)
If I uncomment, user.cart = cart line, then I don't get this error. The moment I try to update the cart field, I get this error. I tried updating the cart field in different formats, but all failed.
I tried directly pushing to the cart field, yet I get the same error:
user.cart.push({ product_id: product._id, quantity: req.body.quantity})
I also tried to directly update the cart with a MongoDB query, but I still get the same error:
await User.updateOne(
{_id: user._id},
{ $push: { cart: { product_id: product._id, quantity: req.body.quantity } }}
)
I figured out what the problem was. Sorry for the trouble. I should've mentioned I was testing the API with jest tests. Turns out there was an error in the tests, that I was able to debug after adding a --detectOpenHandles tag to the npm test script.
I have a simple form that posts to a route, and I'm trying to take the object from that form data and create a new document in my mongoDB using mongoose.
The controller for this functionality looks like:
module.exports.newItem = async (req, res) => {
const formData = req.body.item;
const curbsideItem = new CurbsideItem(formData);
console.log(curbsideItem);
await curbsideItem.save();
res.redirect(`/items/${curbsideItem._id}`);
}
And the console.log(curbsideItem) looks like:
{"name":"Test","location":{"addressLineOne":"test","addressLineTwo":"","city":"Test","state":"PA","zip":15000},"category":"furniture","details":"Random Details Here","image":"No Img","_id":"630a6b2eb7a51d9b2e17e2ef","__v":0}
but for some reason, I think the image string value is trying to be casted into an ObjectId as I'm getting the following error that crashes my app:
const castError = new CastError();
^
CastError: Cast to ObjectId failed for value "No Img" (type string) at path "_id" for model "CurbsideItem"
...
messageFormat: undefined,
stringValue: '"No Img"',
kind: 'ObjectId',
value: 'No Img',
path: '_id',
reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
I don't understand why this is occuring, I've been stuck on this for two hours now and googleing hasn't helped. My schema looks fine, I'm really not sure what to do here.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const curbsideItemSchema = new Schema({
name: {
type: String,
required: true
},
location: {
addressLineOne: {
type: String,
required: true,
},
addressLineTwo: {
type: String
},
city: {
type: String,
required: true
},
state: {
type: String,
required: true
},
zip: {
type: Number,
required: true
}
},
category: {
type: String,
enum: ['furniture', 'clothing', 'toys', 'entertainment', 'other'],
required: true
},
details: {
type: String,
required: true,
maxLength: 500
},
image: {
type: String,
required: true
}
});
module.exports = mongoose.model('CurbsideItem', curbsideItemSchema);
Any help or a pointer in the right direction would be massively appreciated!
So I am trying to create an index in my messageSchema
var messageSchema = new Schema({
senderName : String,
content : String,
reply : String,
date: { type: Date, default: Date.now() },
room : { type: Schema.Types.ObjectId }
});
// this is how to tried to create the index
messageSchema.createIndex({content : "text"}, function(err, data){
console.log(err);
console.log(data);
});
//Also tried
messageSchema.createIndex({content : "text"});
//tried this too
messageSchema.createIndex({"content" : "text"});
The error I keep on getting is
TypeError: messageSchema.createIndex is not a function
Can anyone help me with this.
It seems you are using mongoose. Under the hood,
Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
In the mongo shell, collection.createIndex() works, but in mongoose you need to use mySchema.index(). Mongoose will do the work.
See here for more information: http://mongoosejs.com/docs/guide.html.
from mongoose:
var messageSchema = new Schema({
senderName : String,
content : { type: String, index: true },
reply : String,
date: { type: Date, default: Date.now() },
room : { type: Schema.Types.ObjectId }
});
messageSchema.index({content: 'text'});
The method you are looking for is called index, not createIndex
My schema looks like the following:
User Schema {
name: String,
email: String
}
Job Schema {
title: String,
owner: { type: Schema.Types.ObjectId, ref: 'User' },
helper: { type: Schema.Types.ObjectId, ref: 'User' }
}
Both Users and Jobs use ObjectId's as their ID type.
Part of my application requires me to query the job collection for jobs that fit certain criteria. As part of this query I perform a population of the referenced user documents. Somethings like the following:
Job
.find(query, null, options)
.populate('owner helper', 'name email')
.sort(sort)
.exec(err, function(results) {
...Do Something with populated documents
})
However, this is throwing an error.
{ message: 'Cast to ObjectId failed for value "b" at path "_id"',
name: 'CastError',
type: 'ObjectId',
value: 'b',
path: '_id' }
I have checked all of the user object's ids and they all seem valid. I don't understand what could be causing this error.
Any help would be appreciated.
I am using nodejs, mongoose and I trying to build a shema that contains a reference to itself via parent. Parent should be a reference to DataType.
var DataTypeSchema = new Schema({
_id: String,
label: { type: String, required: true },
comment: { type: String },
url: { type: String, required: true },
parent: { type: Schema.Types.ObjectId, ref: 'DataType' },
values: []
});
var DataType = mongoose.model('DataType', DataTypeSchema);
module.exports.DataType = DataType;
Every DataType has own ID(not generated by mongo) and I think this is a place where it causes problems. It throws me an error cast to objectid failed for value "Number" at path "parent", where Number is object with ID "Number" already saved in DB.
Thanks
The type of the parent reference must match the type of the _id in the model it references. So instead of Schema.Types.ObjectId it should be String:
...
parent: { type: String, ref: 'DataType' },
You can try this
parent: [ this ]
It works