the first document i am creating with this model is good but when creating second document using this model i am getting this error i tried change the _id to id and thats didn't work
const classSchema = new Schema({
prettyId: {
type: Number,
},
name: {
type: String,
required: true,
},
students: [
{
name: {
type: String,
},
_id: {
type: Schema.Types.ObjectId,
ref: "Student",
},
prettyId: {
type: Number,
},
},
],
teachers: [
{
_id: {
type: Schema.Types.ObjectId,
ref: "Teacher",
},
name: {
type: String,
},
prettyId: {
type: Number,
},
},
],
});
classSchema.plugin(AutoIncrement, {
id: "classId",
inc_field: "prettyId",
start_seq: 10000,
inc_amount: 1,
disable_hooks: false,
});
the error i am getting is
return callback(new error_1.MongoServerError(res.writeErrors[0]));
^
MongoServerError: E11000 duplicate key error collection: school.classes index: teachers.id_1 dup key: { teachers.id: null }
{
index: 0,
code: 11000,
keyPattern: { 'teachers.id': 1 },
keyValue: { 'teachers.id': null },
[Symbol(errorLabels)]: Set(0) {}
}
the controller which i create from it the class
exports.newClass = async (req, res, next) => {
const { name } = req.body;
const myClass = new Class({
name: name,
teachers: [],
students: [],
});
await myClass.save();
res.json({ message: "class createad", myClass });
};
It often happens when you have previously used the collection with different parameters. A quick fix would be to delete the collection and try to see if it works.
Related
I have a problem while querying mongodb with nested multiple objects.
I am trying like this
Project.find()
.then((project) => {
RoadMap.find({
scheduledDate: {
$gte: new Date(req.params.gte), $lt: new
Date(req.params.lt)
}
})
.populate("roadMap", "_id title")
.populate("projectId", "_id title photo ")
.exec((err, roadmap) => {
if (err) {
return res.status(422).json({ error: err });
}
res.json({ project, roadmap });
});
})
.catch((err) => {
return res.status(404).json({ error: "project not found" });
});
I am getting results like this
{
project: {
}
roadmap: [{}{}]
}
but I want to achieve like this
{
project: {
_id:
title:
roadmap: [{},{}]
}
}
this is my schema:
projectShema:
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema.Types;
const projectSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
photo: {
type: String,
required: true,
},
caption: {
type: String,
},
postedBy: {
type: ObjectId,
ref: "User",
},
news: [
{
type: ObjectId,
ref: "News",
},
],
roadMap: [
{
type: ObjectId,
ref: "RoadMap",
},
],
},
{ timestamps: true }
);
mongoose.model("Project", projectSchema);
roadMapSchema:
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema.Types;
const roadmapSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
postedBy: {
type: ObjectId,
ref: "User",
},
projectId: { type: ObjectId, ref: "Project" },
categoryName: { type: String },
status: {
type: String,
default: "created",
},
},
{ timestamps: true }
);
mongoose.model("RoadMap", roadmapSchema);
I am not sure how to achieve the results, do I need to change schema or it is possible here also?
thank you
What im trying to do is to push the location and the status of the user in an array in a Schema.
The reason I'm doing that is to store all the user locations in a schema(like a history location)
When I create a location I use the method findOneAndUpdate().
controller/auth.js
exports.addLocation = asyncHandler(async (req, res, next) => {
const {phone, locations, status} = req.body;
const theLocation = await User.findOneAndUpdate(
{ phone },
{ locations, status },
{ new: false }
)
res.status(200).json({
success: true,
msg: "A location as been created",
data: theLocation
})
})
models/User.js
const UserSchema = new Schema({
phone: {
type: String,
unique: true,
},
createdAt: {
type: Date,
default: Date.now
},
code: {
type: Number,
max: 4
},
fullName: {
type:String
},
gender: {
type:String
},
birthdate: {
type:String
},
locations: [
{
location: {
latitude: {type:Number},
longitude: {type:Number},
},
status: {
type: String
},
createdAt: {
type: Date,
default: Date.now,
}
}
],
});
So when a new item is stored, the previous one is deleted.
How can I save the previous item to another MongoDB field?
You can use $push at your query like:
User.findOneAndUpdate(
{ phone: "0912341234" },
{
$push: {
locations: {
location: {
latitude: 10,
longitude: 10,
},
status: "online",
},
},
},
{ new: true },
);
I want to update the type: reported to type: pending under the reportStatus, but when I try it on postman I keep on getting
n:1 ,n:modified:1 and ok:1
report: [
{
category: {
type: mongoose.Schema.Types.ObjectId,
ref: "CrimeCategory",
required: true,
},
location: {
type: mongoose.Schema.Types.ObjectId,
ref: "Location",
required: true,
},
reportText: {
type: String,
required: true,
},
reportStatus: {
type: mongoose.Schema.Types.Mixed,
default: function () {
return [
{ type: "reported", date: new Date(), isCompleted: true },
{ type: "pending", isCompleted: false },
{ type: "investigating", isCompleted: false },
{ type: "solved", isCompleted: false },
];
},
},
},
],
This is the controller where I am trying to update the types that is in the model, what am I doing wrong?
const crimeReport = require("../../model/crimereport");
exports.updateReport = (req, res) => {
crimeReport
.updateOne(
{ _id: req.body.reportId, "report.reportStatus": req.body.type },
{
$set: {
"report.reportStatus.$": [
{
type: req.body.type,
date: new Date(),
isCompleted: true,
},
],
},
}
)
.exec((error, report) => {
if (error) return res.status(400).json({ error });
if (report) {
res.status(200).json({ report });
}
});
};
The postman post request:
{
"reportId": "607b2b25876fa73ec4437440",
"type":"pending"
}
This is the post result from postman:
{
"report": {
"n": 0,
"nModified": 0,
"ok": 1
}
}
It seems like, you are sending reportId in the body of post request as a string while the Mongodb document's id is of type ObjectId. You need to typecast the reportId into ObjectId, before querying to Mongodb. Since you are using Mongoose, this is the way it should be done:
mongoose.Types.ObjectId(req.body.reportId)
how can I update many orderStatus instead of only one?
request.body.type is by default string and contains only one type;
and when isCompleted for the type go true I want even for previous enum index isCompleted go true
is it possible or do I need to modify it in the front-end?
here is the code
const orderSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
orderStatus: [
{
type: {
type: String,
enum: ["ordered", "packed", "shipped", "delivered"],
default: "ordered",
},
date: {
type: Date,
},
isCompleted: {
type: Boolean,
default: false,
},
},
],
}
exports.updateOrder = (req, res) => {
Order.updateOne(
{ _id: req.body.orderId, "orderStatus.type": req.body.type },
{
$set: {
"orderStatus.$": [
{ type: req.body.type, date: new Date(), isCompleted: true },
],
},
}
).exec((error, order) => {
Hey You can use updateMany() operation
db.collection.updateMany(
<query>,
{ $set: { status: "D" }, $inc: { quantity: 2 } },
...
)
I am using comment array in my schema as fallows. I want to push comments data into that comment array using nodejs api
var Schema = mongoose.Schema;
var myfeeds = new Schema({
title: {
type: String,
required: true
},
feed: {
type: String,
required: true
},
createdBy: {
type: String,
required: true,
unique: true
},
createdDate: {
type: Date,
required: true,
default: Date.now()
},
comment: [
{
commentBy: {
type: String
},
commentText: {
type: String
},
createdDate: {
type: Date
}
}
],
likes: [
{
likesCount: {
type: Number,
required: false
},
likeBy: {
type: String,
required: false
}
}
]
});
I want to push object to this comment array. so, for that I did in this way please tell me if anything wrong in this
let _id = req.body.id;
let commentBy = req.body.commentedBy;
let commentedText = req.body.commentedText;
let commentedDate = req.body.commentedDate;
let data = {
commentBy: commentBy,
commentText: commentedText,
createdDate: commentedDate
};
MyFeeds.findByIdAndUpdate(
{ _id: _id },
{
$push: {
comment: data
}
}
)
.then((result) => {
res.status(200).json({
status: result
});
})
.catch((err) => {
res.status(500).json({
status: 'invalid',
err: err
});
});
but only id are inserted into that comment array but not the required content
"comment": [
{
"_id": "5badfd092b73fa14f4f0aa7c"
},
{
"_id": "5badfd102b73fa14f4f0aa7d"
},
{
"_id": "5badfd142b73fa14f4f0aa7e"
},
{
"_id": "5badfd31500fb11bb06b4c8a"
},
{
"_id": "5badfd35500fb11bb06b4c8b"
},
{
"_id": "5badff3d439a151190d62961"
}
],