Preventing Duplicate ID Creation in MongoDB - javascript

In my Node/MongoDB backend I have a model that references a payers collection, like so:
clients: [{ id: { type: mongoose.Schema.Types.ObjectId, ref: 'clients' } }],
This is working, in that an id that's a reference to the correct "client" gets inserted. However, what's also happening is that mongo is auto-inserting a mongo ID. So in the document in question I end up with this:
clients: [{
id: 6b8702ad021ba27d4a3b26h9, // my correct ref object ID
_id: 4n8702bv036ba12g6a3b28f4 // an additional object ID auto inserted by mongo
}]
How do I prevent the auto insertion of the mongo ID in a situation like this? And, relatedly, if I were to use an _ in my original ref, like so:
clients: [{ _id: { type: mongoose.Schema.Types.ObjectId, ref: 'clients' } }],
...would this prevent this from happening to begin with, since there would already be a value for "_id"? In other words, would Mongo then NOT auto insert another ID? If so, that's the route I will take.

Yes, overwriting _id will work. Just be aware that _id is your database's primary key, so it needs to be unique or Mongo will throw an error.

Related

How to add same data object to a document (MongoDB)

I am trying to uniquely store data for each server in a database, I want to be able to store multiple of the same data object. I am only able to store one because if I attempt to store another one it just replaces it, which is the issue here.
Schema
const schema = new mongoose.Schema({
reactionRole: {
type: Object,
required: false,
}
});
Screenshot of the Data
Trying to Accomplish
I want to be able to store the same object here but with different data obviously, would I have to make the schema take a Array and just insert it? I am not really sure how to work around this, thanks!
Example
This is how I want the data to be, the option to be able to add more onto the document instead of replacing it. Should I use an array or what's a solution?
reactionRole: {
<Role.name> config 1: {
Enabled: true,
Added_By: id,
MessageID: msg.id,
Emoji: <emoji>,
Role: id,
},
<Role.name> config 2: {
Enabled: true,
Added_By: id,
MessageID: msg.id,
Emoji: <emoji>,
Role: id,
}
}
I resolved this. I changed the schema to an array and sent the data as objects.

MongoDB: How can populate reference, and delete element in array after based on the ID of the reference

So I have a situation where I need to delete elements in an array of reference / ObjectIds, but the delete condition will be based on a field in the reference.
For example, I have schemas like the following:
const UserSchema = new mongoose.Schema({
firstName: String,
lastName: String,
homeFeeds:[{type: Schema.Types.ObjectId, requried: true, ref: "Activity"}];
}); // User , is the referenece name
const ActivitySchema = new mongoose.Schema({
requester: {type: Schema.Types.ObjectId, requried: true, ref: "User"},
message: String,
recipient: {type: Schema.Types.ObjectId, requried: true, ref: "User"},
}) // Activity, is the reference name
Now I need to delete some of the homeFeeds for a user, and the ones that should be deleted need to be by certain requester. That'll require the homeFeeds (array of 'Activity's) field to be populated first, and then update it with the $pull operator, with a condition that the Activity requester matches a certain user.
I do not want to read the data first and do the filtering in Nodejs/backend code, since the array can be very long.
Ideally I need something like:
await User.find({_id: ID})
.populate("homeFeeds", "requester")
.updateMany({
$pull: {
homeFeeds.requester: ID
}
});
But it does not work, Id really appreciate if anyone can help me out with this?
Thanks
MongoDB doesn't support $lookup in update as of version v6.0.1.
MongoServerError: $lookup is not allowed to be used within an update.
Though, this doesn't have to do with Mongoose's populate as populate doesn't depend on $lookup and fires additional queries to get the results. Have a look at here. Therefore, even if, you could achieve what you intend, that is avoiding fetching a large array on nodejs/backend, using mongoose will do the same thing for you behind the scenes which defeats your purpose.
However you should raise an issue at Mongoose's official github page and expect a response.

Mongoose, $pull an element from nested array and update document based on the presence of the element

I am working on a mongoose schema similar to this:
const actionSchema = {
actions: {
type: [{
actionName: {
type: String,
required: true
},
count: {
type: Number,
default: 0,
required: true
},
users: [{
type: Schema.Types.ObjectId,
ref: 'User'
}]
}]
}};
It is a nested schema of a post schema.
Here, actions are dynamically generated and number of people does that action are maintained by count and their identity is maintained by users array.
As you see, actions is an array of objects which further contain users array.
I want to check if a provided user id is present in any of the action object and then remove it from array and also reduce the count.
Being totally new to mongoose and mongodb, one simple way I see is to find the post using Post.findById() which has to be updated, run js loops, update the post and call .save(). But it can be very costly when users array has thousands of user ids.
I tried .update() but can't understand how to use it in this case.
How about adding a method to the Post Model (like postSchema.methods.removeUserAction)? This gives access to document from this and allows to update the document and thus call .save(). Does it loads the full document to the client node application?
So please suggest the right way.
Thank you.
You should simplify your model, for example
// Model - Actions Model
const actionSchema = {
actionName: {
type: String,
required: true
},
user: {
type: Schema.Types.ObjectId,
ref: 'User'
}
};
And you can easily get the total actions via Model.count(), get specific action count with Model.count({ actionName: 'action name'}), and removing entries with Model.delete(condition). Unless there's a reason why you have it modeled this way.

Mongoose: Populate path using field other than _id

By default mongoose/mongo will populate a path using the _id field, and by it seems like there is no way to change the _id to something else.
Here are my two models which are connected with one-to-many relationship:
const playlistSchema = new mongoose.Schema({
externalId: String,
title: String,
videos: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Video',
}],
});
const videoSchema = new mongoose.Schema({
externalId: String,
title: String,
});
Normally, when querying a playlist you would populate videos just with .populate('videos'), but in my case I would like to use the externalId field instead of the default _id. Is that possible?
As far as I know, the way to achieve this with mongoose presently is by using virtuals. When populating virtuals, you can specify the localField and foreignField to whatever you want, so you are no longer bound to the default _id as foreignField. More details about this here.
For the scenario described in your question, you would need to add a virtual to the playerlistSchema, something like this:
playlistSchema.virtual('videoList', {
ref: 'Video', // The model to use
localField: 'videos', // The field in playerListSchema
foreignField: 'externalId', // The field on videoSchema. This can be whatever you want.
});
Now, whenever you query for player lists, you can populate the videoList virtual to get the referenced video documents.
PlaylistModel
.findOne({
// ... whatever your find query needs to be
})
.populate('videoList')
.exec(function (error, playList) {
/* if a playList document is returned */
playList.videoList; // The would be the populated array of videos
})

How can I insert an array into my MongoDB stitch if I already have IDs defined?

I get my data from an API and I parse the JSON object which leads to an array. [{ id: "24qera", name: "john"}, {id: "rq3raa34", name: "jess"}}. I have over 20 documents which I am trying to store.
I have my array called data and my db variable connected to my database and my collection connected as well. I use the line collection.insertMany( json ); When I use that, I now have two IDs which is my objectID and my array ID.
var db = dbService.db("GitLab-db");
var collection = db.collection("User");
collection.insertMany(fdata);```
expectation: {
_id:ObjectId("24qera"),
name: "john"
},
{
_id:ObjectId("rq3raa34"),
name: "jess"
}
output: {
_id:ObjectId("jfakej23j4q3wa4")
id: "24qera",
name: "john"
},
{
_id:ObjectId("akjk34qq453")
id: "rq3raa34",
name: "jess"
}
I guess you cant really manipulate the _id which is auto generated by mongodb on storing the data in array....you can just ignore the _id and work with the id which is being stored
MongoDB automatically inserts an _id value if not provided. This is hard-coded behavior to ensure that there is always a unique primary key available for retrieving specific documents. You cannot change this behavior.
You can, however, simply ignore the _id field, or even strip it out completely from returned results by adding a projection option. For example, in the MongoDB shell you can run the following:
db.User.find({name: "jess"}, {_id: 0})

Categories

Resources