Syntax error Unexpected token ILLEGAL Mongo Console - mongodb

I'm trying to remove a document from an array threads that is a field in the collection's head document.
In Mongodb console I write following query:
db.inboxes.update({}, { $pull: {threads: {"_id":ObjectId(”5550b41ce7c33013c8000006”)}}})
But I keep getting:
Unexpected token ILLEGAL
It's driving me crazy. The Collection's schema is as following:
var inboxSchema = mongoose.Schema({
user: {
type: mongoose.Schema.ObjectId,
ref: 'userSchema',
required: true
},
threads: [{
name: String,
guid: String,
with: {
_id: {
type: mongoose.Schema.ObjectId,
ref: 'userSchema'
},
name: {
username: String,
firstname: String,
lastname: String
},
email: {
type: String,
match: /\S+#\S+\.\S+/
}
},
messages: [{
heading: String,
sent: {
type: Date,
default: Date.now
},
from: {
type: mongoose.Schema.ObjectId,
ref: 'userSchema'
},
to: {
type: mongoose.Schema.ObjectId,
ref: 'userSchema'
},
body: String
}],
updated: {
type: Date,
default: Date.now
},
unreadMessage: Boolean
}]
});

Take a look at your query
db.inboxes.update({}, { $pull: {threads: {"_id":ObjectId(”5550b41ce7c33013c8000006”)}}})
in ObjectId argument you have wrong quote marks ” instead of ". Replace them and you will get rid of the error :)

Related

Id is created for every nested objects in documents of a collection in mongodb via mongoose

I have a user schema. While saving document, for every nested object (quizHistory,record & responses) in document, mongoose add _id field automatically. For ref- quizHistory path
const userSchema = new Schema({
firstName: { type: String, required: true ,trim:true},
lastName:{ type: String, required: true ,trim:true},
email: { type: String, unique: true, required: true },
isUser: { type: Boolean, default: true },
password: String,
quizHistory: [{
quizId: { type: Schema.Types.ObjectId, ref: 'Quiz' },
record: [{
recordId:{ type: Number},
startTime: { type: Date },
responses: [{
quesId: { type: Schema.Types.ObjectId, ref: 'Question' },
answers: [Number]
}],
score: Number
}],
avgScore: Number
}]
})
Mongoose create virtual id by default(guide id).
Add this line to your schema.
_id : {id:false}

Pushing into array mongoose and mongo

I get the following error Cannot create field 'likes' in element whenever I am trying to push into my likeList array nested inside my comments.
When executing the following:
Feed.findOneAndUpdate(
{
owner: req.body.authorId,
"posts.comments.commentList._id": req.body.commentId
},
{
$push: {
"posts.$.comments.commentList.likes.likeList": {
user: req.user._id,
avatar: req.user.profile.profile_picture.url,
name: req.user.name
}
)
And my schema is as follows:
Feed Schema
owner: {
type: Schema.Types.ObjectId,
ref: "userType"
},
posts: [
{
author: {
userType: {
type: String,
enum: ["IndustryPartner", "User", "School"]
},
user: {
type: Schema.Types.ObjectId,
ref: "posts.author.userType", //<- This may cause an issue, if there are any issues with retrieving user fields, CHECK THIS
required: true
},
name: { type: String, required: true },
avatar: { type: String, required: true }
},
comments: {
totalComments: { type: Number, default: 0 },
commentList: [
{
likes: {
totalLikes: { type: Number, default: 0 },
likeList: [ <---//Trying to push here
{
user: { type: Schema.Types.ObjectId, ref: "User" },
avatar: { type: String },
name: { type: String },
date: {
type: Date,
default: Date.now
}
}
]
...
I am not sure if it's an issue with the query I am using in the first parameter to filter.
Update entire error message
It is odd because it appears that it is actually finding the correct commentList to go to, but is unable to access the likes field within the array itself. Am I wrong assuming that this should be able to step through it? posts.$.comments.commentList.likes.likeList
{ MongoError: Cannot create field 'likes' in element {commentList: [ { likes: { totalLikes: 0, likeList: [] },
_id: ObjectId('5cf6b3293b61fe06f48794e3'), user: ObjectId('5c9bf6eb1da18b038ca660b8'), avatar: "https://sli.blob.core.windows.net/stuli/
profile-picture-e1367a7a-41c2-4ab4-9cb5-621d2008260f.jpg", name: "Luke Skywalker", text: "Test comment from Luke", repliesToComment: [], date: new Date(1559671593009) } ]}
After further research, it appears the positional operator is no longer useful after stepping through 2 levels of arrays. So, the solution would be to use JS to change push the values into the array and then save them.

how to search for any value in the document

I want to search for all value present without specifying key explicitly. Is it possible with this type of schema? If so, how can I write my query. I tried to write query with other refs but I am unable to write without specifying key for each.
const pschema = new Schema({
user: {
type: Schema.Types.ObjectId, // combine by id
ref: "users" //existing model reference
},
company: {
empNo: {
type: Number,
required: true
},
status: {
type: String,
required: true
},...
},
personal: {
gender: {
type: String
},
dob: {
type: Date
},...
},
skills: {
type: [String],
required: true
},
experience: [
{
title: {
type: String,
required: true
},
company: {
type: String,
required: true
},
location: {
type: String
}...
}
],
education: [
{
school: {
type: String,
required: true
},
degree: {
type: String,
required: true
},
specialization: {
type: String
},..
}
],
social: {
twitter: {
type: String
},
facebook: {
type: String
},
linkedin: {
type: String
},...
}
});
For example: If i give linkedin url if should search in social-linkedin and same if i give c it should search in skills array

Reference 2 collection in 1 field

Is it possible to have more than 1 reference in a field. If not, is there anyway good way to make it?
I tried this one: (2 reference in productStaff)
var productSchema = mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
index: true
},
productNumber: {
type: Number,
required: true
},
client_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Client',
required: true
},
receiveDate: {
type: Date,
required: true
},
paymentDate: {
type : Date
},
deadline: {
type: Date,
required: true
},
remark: {
type: String,
default: null
},
productStaff: [{
staff: {
type : mongoose.Schema.Types.ObjectId,
ref: 'Staff'
},
assignment: {
type : mongoose.Schema.Types.ObjectId,
ref: 'Assignment'
}
}],
productItem: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'ProductItem',
default: null
}],
registrationDate: {
type: Date,
default: Date.now
}
});
But i got this error when adding the data:
Error: "Product validation failed: productStaff: Cast to Array failed for value \"[ { staff: '594b63b184e6290c386baa3f',\n assignment: '594b63b184e6290c386baa3f' },\n { staff: '594b63b184e6290c386baa3g',\n assignment: '594b63b184e6290c386baa3g' } ]\" at path \"productStaff\""
I'm made it this way because I need to save the staff who will do the product with their corresponding assignments.
Thanks a lot.

Mongoose: How to query objects inside populate? [duplicate]

This question already has answers here:
Querying after populate in Mongoose
(6 answers)
Closed 6 years ago.
I have this route for searching partial user input for orderId.
ordersAdminRouter.route('/searchorder/:term')
.get(function(req, res){
term = req.params.term;
console.log(term);
Orders.find({orderId: new RegExp(term)})
.populate({ path: 'userPurchased products.product', select: '-username -password' })
.exec(function(err, orders){
if (err) throw err;
console.log(orders);
res.json(orders);
});
});
Here is my schema
var orderSchema = new Schema({
orderId: { type: String },
userPurchased: { type: Schema.Types.ObjectId, ref: 'users' },
products: [
{
product: { type: Schema.Types.ObjectId, ref: 'products' },
size: { type: String, required: true },
quantity: { type: Number, required: true },
subTotal: { type: Number, required: true }
}
],
totalQuantity: { type: Number },
totalPrice: { type: Number },
modeOfPayment: { type: String },
shippingAd: { type: String },
refNumber: { type: String },
isDone: { type: Boolean, default: false },
orderStatus: { type: String, default: 'Pending' },
dateOrdered: { type: Date, default: Date.now() },
fromNow: { type: String }
});
Now I need to search for the firstname and lastname inside userPurchased which I only get when I populate. How can search it?
I could not understand what kind of information you are saving in the 'userPurchased' field. I assume the users are in a different collection and you're only persisting the id of the user in the userPurchased. If you are just placing the id, you can search using the following query:
orderSchema.find({userPurchased : 'id'})
If you're putting an object with fields, there's no mystery either. Just use the . operator. For example:
orderSchema.find({userPurchased.firstName : 'name'})
Hope it helped you