I have this document in mongo atlas
_id: 5f8939cbedf74e363c37dd86,
firstname: "Person",
lastname: "Person lastname",
sex: "Masculino",
age: "20",
birthDay: 2020-10-07T00:00:00.000+00:00,
vaccines: Array
0:Object
dose: Array
_id: 5f8939cbedf74e363c37dd87
vaccine:5f7023ad96f7ed21e85be521
createdAt:2020-10-16T06:12:27.726+00:00
updatedAt:2020-10-16T06:12:27.726+00:00
1:Object
dose:Array
_id:5f893a9ca98e97188c93fea8
vaccine:5f70259796f7ed21e85be523
2:Object
dose:Array
_id:5f893acda98e97188c93fea9
vaccine:5f7023ad96f7ed21e85be521
This is my mongoose schema
const mySchema = new Schema({
firstname: {
type: String,
required: true,
},
lastname: {
type: String,
required: true,
},
sex: {
type: String,
required: true,
},
age: {
type: String,
required: true,
},
birthDay: {
type: Date,
required: true,
},
vaccines: [
{
type: new Schema(
{
vaccine: {
type: Schema.ObjectId,
ref: "Vaccine",
},
dose: Array,
},
{ timestamps: true }
),
},
],
});
every time I add a new person the vaccines array gets one new object with the timestamp as you can see, in my js file I use this code:
const addPerson = (person) => {
const myPerson= new Model(person);
return myPerson.save();
};
Then when I add a new vaccine for the same person this does not get the timestamp, I'm using this code for that:
const addPersonVaccine = async ({ params, body }) => {
if (!params) return Promise.reject("Invalid ID");
const vaccines = [body];
const foundPerson = await Model.updateOne(
{
_id: params,
},
{
$push: {
vaccines: vaccines,
},
}
);
return foundPerson;
};
This is what my body inside vaccines array has:
[ { vaccine: '5f72c909594ee82d107bf870', dose: 'Primera' } ]
The problem is that I have no results about the next timestamps, as you can see in my mongo atlas document:
1:Object
dose:Array
_id:5f893a9ca98e97188c93fea8
vaccine:5f70259796f7ed21e85be523
2:Object
dose:Array
_id:5f893acda98e97188c93fea9
vaccine:5f7023ad96f7ed21e85be521
Is that the best way to implement timestamps in subdocuments or sub schemas?
I will appreciate your answers, thnks 👏
You can use mongoose schema timestamps options to the inner schemas
const mongoose = require("mongoose");
const forumSchema = new mongoose.Schema(
{
title: { type: String, required: true },
biddings: [
{
type: new mongoose.Schema(
{
biddingId: String,
biddingPoints: Number
},
{ timestamps: true }
)
}
]
},
{ timestamps: true }
);
const Forum = mongoose.model("Forum", forumSchema);
module.exports = Forum;
for more Mongoose schema set timestamp on nested document
Related
I am trying the aggregation in mongoose. When I run that aggregation, it show the error. What am I missing?
const data = await Rooms.aggregate([{ $match: { adminID: "1234" } }]);
Error is like that
MongoInvalidArgumentError: Method "collection.aggregate()" accepts at most two arguments
Edit -- code for Rooms Schema
const mongoose = require('mongoose');
const Rooms = new mongoose.Schema(
{adminID: {
type: String,
required: true,
},
roomID: {
type: String,
required: true,
},
roomName: {
type: String,
required: true,
},
users: [
{
id: {
type: String,
required: true,
unique: true,
},
},
],
},
{ timestamps: true } );
module.exports = mongoose.model("rooms", Rooms);
solution 1 : downgrade mongoose to version 5
solution 2 :
const data = await Rooms.aggregate([{ $match: { adminID: "1234" } }],"adminID roomID roomName users");
in new version second argument is selected fields in out put,
or use :
const data = await Rooms.aggregate.match({ adminID: "1234" } )
I'm new to mongoDB and backend stuffs. I've a nested MongoDB model schema. I need to update, delete and add in that nested objects/array. How can I do that ?
How can I delete/add/update item from columns array and resume array.
const userSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
},
columns: [
{
title: {
type: String,
required: true,
},
resumes: [
{
name: {
type: String,
required: true,
},
resume: {
type: String,
required: true,
},
},
],
},
],
});
const Users = mongoose.model('Users', userSchema);
This is my schema
To add new item to the columns array:
let newData = {title: "New Title", resumes: []}
let userData = await User.findByIdAndUpdate(userID, {
$push: {
columns: newData,
},
});
To add new item to the resumes array inside columns:
let newData = {name: "New Name", resume: "New Resume"}
let userData = await User.updateOne(
{
_id: mongoose.Types.ObjectId("60f54774761788cd80f56xxx"),
"columns._id": mongoose.Types.ObjectId("60f54774761788cd80f56xxx"),
},
{
$push: { "columns.$.resumes": newData },
}
);
Similarly, you can use $pull operator to remove an object from the array, and $(update) to update the element inside the array
I am pretty new at mongoose and nodejs so I was doing my project referring to mongoose document. I want to remove a particular subdocument in the comment array by identifing the subdocument with its id. I trried doing it using "pull" as well as "id" method as shown in the image. I couldn't find any mistake in my syntax as well but still it is working.
This is sample document from my db:
{
comments: [
{
replyComment: [],
_id: 601a673735644c83e0aa1be3,
username: 'xyz123#gmail.com',
email: 'xyz123#gmail.com',
comment: 'test123'
},
{
replyComment: [],
_id: 601a6c94d1653c618c75ceae,
username: 'xyz123#gmail.com',
email: 'xyz123#gmail.com',
comment: 'reply test'
},
{
replyComment: [],
_id: 601eb7ba7233015d7090c6bf,
username: 'xyz123#gmail.com',
email: 'xyz123#gmail.com',
comment: 'test comment'
},
{
replyComment: [],
_id: 601ec090f5f22d75b41bec7b,
username: 'xyz123#gmail.com',
email: 'xyz123#gmail.com',
comment: 'test comment123'
}
],
_id: 601a3b8038b13e70405cf9ea,
title: 'latest test',
snippet: 'latest test snippet',
body: 'latest test body',
createdAt: 2021-02-03T05:58:24.123Z,
updatedAt: 2021-02-07T06:56:53.902Z,
__v: 15
}
By doing this test findById("601a3b8038b13e70405cf9ea") and console.log(result)
My topicSchema file:
const mongoose = require('mongoose');
const Schema =mongoose.Schema;
const topicSchema = new Schema({
title: {
type: String,
required: true
},
snippet: {
type: String,
required: true
},
body: {
type: String,
required: true
},
comments: {
type: Array,
required: false
}
}, {timestamps: true},{ versionKey: false });
const Topic = mongoose.model('Topic', topicSchema);
module.exports = Topic;
My commentSchema file:
const mongoose = require('mongoose');
const Schema =mongoose.Schema;
const comSchema = new Schema({
username: {
type: String,
required: true
},
email: {
type: String,
required: true
},
comment: {
type: String,
required: true
},
replyComment: {
type: Array,
required: false
},
}, {timestamps: true},{versionKey: false});
const Comm = mongoose.model('comm', comSchema);
module.exports = Comm;
You have not defined topic and don't using topic = result, with , because it's not necessary
so doing like this :
result.comments.id(commId).remove();
result.save()
if you want to using topic just try
let topic = result;
topic.comments.id(commId).remove();
topic.save()
for this document you can using update and $pull like this:
Topic.updateOne(
{
_id: req.params.id,
},
{
$pull: {
"comments" : { _id: req.params.id1 }
},
},
).then((res)=>{
console.log(res)
}).catch(err=>{
console.log(err)
});
if you can use async/await just try
app.delete('/topic/:id/comments/:id1',async(req,res)=>{
let result = await Topic.findById(req.params.id);
result.comments.id(req.params.id1).remove();
let finalResult = await result.save()
console.log(finalResult)
})
and with .then() .catch approach:
Topic.findById(res.params.id).then(result=>{
let topic = result;
topic.comments.id(res.params.id1).remove();
topic.save().then(result=>{
console.log(result)
}).catch(err=>console.log(err))
}
).catch(err=>{
console.log(err)
});
NOTE: update the mongodb to 4.4 and uninstall mongoose module and install again
My MongoDB is not getting the data I'm trying to save specifically from the array, every other properties are being saved normally.
Here's my Schema:
const mongoose = require('mongoose');
const SubSchema = new mongoose.Schema({
servicesTitle: {
title: {
type: String
},
description: {
type: String
}
}
});
const AreaSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
text: {
type: String,
required: true
},
imageUrl: {
type: String,
required: true
},
imageDescription: {
type: String,
required: true
},
services: [SubSchema]
});
const Areas = mongoose.model('Areas', AreaSchema);
module.exports = Areas;
How am I handling it?
const { //Getting the info from the form
title,
text,
imageUrl,
imageDescription,
servicesTitle, //ARRAY
servicesDescription //ARRAY
} = req.body;
Then I created a variable called "services" and its value is an array of objects with the servicesTitle and servicesDescription each, like:
[
{
servicesTitle: 'Example1',
servicesDescription: 'lalalallalalala'
},
{
servicesTitle: 'Example2',
servicesDescription: 'lalalallalalala'
},
{
servicesTitle: 'Example3',
servicesDescription: 'lalalallalalala'
}
]
Then I create a new model with these values and save it:
const newAreas = new Areas({
title,
text,
imageUrl,
imageDescription,
services
});
newAreas.save()
.then(areas => {
res.redirect('/areas');
})
.catch(err => console.log(err));
Here's the output: https://i.imgur.com/kD0qfXh.png
So the exactly amount of items are created but the properties aren't saved. There should be 2 properties inside each object, the servicesTitle and servicesDescription.
Your services object needs to be like below, before passing to save function as per your schema
[
{
servicesTitle: 'Example1',
description: 'lalalallalalala'
},
{
servicesTitle: 'Example2',
description: 'lalalallalalala'
},
{
servicesTitle: 'Example3',
description: 'lalalallalalala'
}
]
And your schema should be like
const SubSchema = {
servicesTitle: {
title: {
type: String
},
description: {
type: String
}
}
};
I have a model in mongoose
'use strict';
var mongoose = require('bluebird').promisifyAll(require('mongoose'));
var Schema = mongoose.Schema;
function toLower (v) {
return v.toLowerCase();
}
var Signup = new Schema({
name: { type: String, required: true },
email: { type: String, unique: true, required: true, set: toLower },
position: { type: String },
area: String,
companySize: Number,
created: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Signup', Signup);
I would like to group by created (date formatted to day) and count the number of _ids.
I'm new to mongoose and bluebird... Could anyone provide me with an example? Thx!!!
I managed to get exactly what I wanted:
SignupModel
.aggregate([
{
$group: {
_id: { $week: "$created" },
"count": { "$sum": 1 }
}
}
])
.execAsync()
.then(responseWithResult(res))
.catch(handleError(res));
=> Groups by created (week) and sums them