MongoDB Unique objectId in document [duplicate] - javascript

I'm trying to find documentation, to no avail, on how to create multi-field indexes in Mongoosejs. In particular I have two fields that need to be indexed and unique. What is an example mongoose schema that indexes two fields together?

You call the index method on your Schema object to do that as shown here. For your case it would be something like:
mySchema.index({field1: 1, field2: 1}, {unique: true});

Defining indexes at the schema level is necessary when creating compound indexes.
animalSchema.index({ name: 1, type: -1 });
Reference: http://mongoosejs.com/docs/guide.html#indexes

import { Schema, Document, model } from 'mongoose';
import { IUser } from './User';
import { IMood } from './Mood';
import { ILocation } from './Location';
export interface IUserMoodLocation extends Document {
userId?: IUser['_id'];
moodId?: IMood['_id'];
locationId?: ILocation['_id'];
}
const UserMoodLocationSchema: Schema = new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'User'
},
moodId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Mood'
},
locationId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Location'
}
});
UserMoodLocationSchema.index(
{ userId: 1, moodId: 1, locationId: 1 },
{ unique: true }
);
export const UserMoodLocation = model<IUserMoodLocation>(
'UserMoodLocation',
UserMoodLocationSchema
);

Following command can be used to create compound index for nested json:
db.ACCOUNT_collection.createIndex({"account.id":1,"account.customerId":1},{unique:1})
Mongo json structure is like :
{"_id":"648738"
"account": {
"id": "123",
"customerId": 7879,
"name": "test"
..
..
}
}
I have tested with sample data it is perfectly working as expected.

By the way, the accepted answer is wrong, as per https://stackoverflow.com/a/52553550/129300 you should wrap the field names in single quotes, ie:
mySchema.index({'field1': 1, 'field2': 1}, {unique: true});
Happy Day!

Related

Update boolean value inside of nested array Mongoose

I have a Schema that holds an array of objects for comments and I would like to update the boolean value of the flagged comments accordingly, I have tried updateOne and aggregate but it isn't working out at this point, I have also tried to use $elemMatch but it isn't working.
The comment _id is being pulled from the front end element that has an ID that is the same as the id that needs to be pulled from MongoDB.
Comments Array within the question Schema:
comments: [
{
user: {
type: Object,
},
commentDate: {
type: Date,
default: Date.now()
},
flagged: {
type: Boolean,
default: false
},
flaggedDate:{type: Date},
comment: String,
}
],
function I tried to run last.
const id = req.params.id
const updateFlag = Question.updateOne(
{
comments: [
{
_id: id
}
]
},
{
$set: {
comments: [
{
flagged: req.body.flagged
}
]
}
}
)
Any help would be appreciated!
You can do it with positional operator - $:
db.collection.update({
"comments._id": "3"
},
{
"$set": {
"comments.$.flagged": true
}
})
Working example

How to query a mongo document using mongoose?

MongoDB documents contain an array of objects and what is the best way to query those documents if I want to find and remove an object from an array with some specific value;
Here is an example of the document schema
const mongoose = require("mongoose");
const LibrarySchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
},
books: [
{
type: new mongoose.Schema({
bookName: {
type: String,
required: true,
},
chapterReading: {
type: Number,
default: 1,
required: true,
},
}),
},
],
});
const Library = mongoose.model("Library", LibrarySchema);
exports.Library = Library;
If I want to find and remove a book with some bookName
Use $pull
Example :
Library.update({}, { $pull: { books: { bookName: "Yourbookname" } } })

Mongoose populate nested element inside of multiple arrays

I have the following schema:
const userSchema = new Schema({
...,
categories: [
{
name: {
type: String,
required: true
},
products: [
{
type: mongoose.Types.ObjectId,
required: false,
ref: 'Product'
}
]
}
],
...
}
I want to get all the products a user have.
I have seen more questions about this topic but I don't get it to work.
If you entered your data correctly you can do like this:
let result = await User.findById(id).populate("categories.products").lean()

use mongooseModel.find() on schema that has a Schema.Types.Mixed property

I have trouble using postModel.find() query in a schema that defined as Schema.Types.Mixed.
this is a sample of my schema
const PostSchema = new mongoose.Schema({
//.....
address: {
type: String,
required: true,
},
postDetails: {
type: Schema.Types.Mixed,
required: true,
},
author: {
type: Schema.Types.ObjectId,
ref: 'User',
},
//.....
});
this is a sample document stored in db
{
//.....
"state": "Lakes State",
"address": "some address",
"postDetails": {
"type": "Cages",
"condition": "Used"
},
//......
}
it is giving me an empty array if I use this
const queryObject = {
postDetails: {
type: 'Cages',
},
};
return this.postModel.find(queryObject);
but it gives the desired results if I include all the properties like this
const queryObject = {
postDetails: {
type: 'Cages',
condition: 'Used',
},
};
return this.postModel.find(queryObject);
How do i get all matching posts that have postDetails.type = 'Cages' ? without knowing all available properties inside postDetails
there are some similar questions about this here. but most of them are using arrays instead of an object
You can use dot notation for querying embedded documents
postModel.find({
"postDetails.type": "Cages"
});

Querying nested Schema in Mongodb?

i'm learning MongoDB for a few weeks now and i have still no idea how to query nested documents in my project. I read the MongoDB-docs and googled a lot, but i found no good explanations or tutorials for my problem. Maybe you can help me!
I have three Collections which are referencing each other:
const shipmentSchema = new mongoose.Schema({
item: {
type: String,
required: true,
},
cityId: {
type: mongoose.Schema.Types.ObjectId,
ref: "City",
},
});
const citiesShcema = new mongoose.Schema({
cityName: {
type: String,
required: true,
},
countryId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Countries",
required: true,
},
});
const countriesSchema = new mongoose.Schema({
countryName: {
type: String,
required: true,
},
});
const Shipment_new = mongoose.model("Shipment_new", shipmentSchema);
const Cities = mongoose.model("City", citiesShcema);
const Country = mongoose.model("Countries", countriesSchema);
So, guys I was wondering if there's way to query shipments from a country... I mean I want to get all shipments with in a country. So, I tried to work it solved with my own and this what I tried:
const filterShipment = {
cityId: {
countryId: "5f6bbe558b094c14103a7776",
},
};
const shimpents = await Shipment_new.find(filterShipment);
But this didn't do the work so guys, you may wanna help me out here.... I just want get the shipments of a specific countray? THANKS IN ADVANCE
For querying multiple documents in mongo (Joins in SQL) you need to use $lookup. Based on what i uderstood from question, Below query gives you all the shipments by countryId.
Here is the query. I have also added mongo playground. So that you can run the query. And make some changes if needed.
db.Shipment_new.aggregate([
{
"$lookup": {
"from": "City",
"localField": "cityId",
"foreignField": "_id",
"as": "city"
}
},
{
"$unwind": "$city"
},
{
"$match": {
"city.countryId": 111
}
},
{
"$project": {
item: 1,
city: "$city.cityName",
countryId: "$city.countryId"
}
}
])
Is this what you are looking for?
Here is the Mongo Playground

Categories

Resources