The find() at the end of this code does NOT find the inserted document.
Note: I'm using MongoDB version 3.2.15.
Why not?
How can I change the index or search parameters so that it's found?
db['test'].createIndex(
{
name: 'text',
email: 'text',
phoneNumber: 'text'
},
{
default_language: 'none',
name: 'text_index',
$caseSensitive: false,
$diacriticSensitive: false,
} );
db['test'].insert({
name: 'Chaney Waste Management',
email: 'cliffchaney#gmail.com',
phoneNumber: '(402)555-1212'
});
db['test'].find( {
$text:
{
$search: 'manage',
$language: 'none',
$caseSensitive: false,
$diacriticSensitive: false
}
} ); // Finds nothing! Why?
In case it matters, here is the full result of a db.hostInfo() call:
{
"system" : {
"currentTime" : ISODate("2017-11-09T02:38:45.379Z"),
"hostname" : "Cliff-Surface:3001",
"cpuAddrSize" : 64,
"memSizeMB" : 16310,
"numCores" : 4,
"cpuArch" : "x86_64",
"numaEnabled" : false
},
"os" : {
"type" : "Windows",
"name" : "Microsoft Windows 8",
"version" : "6.2 (build 9200)"
},
"extra" : {
"pageSize" : NumberLong(4096)
},
"ok" : 1.0
}
Related
I have been searching for some hours how to make the ISBN field unique and haven't found a solution. Creating an index gives me the following error. I still didn't understand how these indexes work - I am in the process of learning. If you come with a quick solution let me know!
Attempt to create an index
db.books.createIndex( {ISBN : 1} , {unqiue : true} )
Error
/* 1 */
{
"ok" : 0.0,
"errmsg" : "Error in specification { key: { ISBN: 1.0 }, name: \"ISBN_1\", unqiue: true } :: caused by :: The field 'unqiue' is not valid for an index specification. Specification: { key: { ISBN: 1.0 }, name: \"ISBN_1\", unqiue: true }",
"code" : 197,
"codeName" : "InvalidIndexSpecificationOption"
}
Schema
db.createCollection("books", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [
"ISBN",
"title"
],
properties: {
_id: {},
ISBN: {
bsonType: "string",
// make this unique
},
title: {
bsonType: "string",
},
},
},
},
});
I am a bigenner in mongoose, I implement a concept of comment. In fact, I create a schema comment in which I identify the different fields, as it is shown:
import mongoose from 'mongoose';
/* eslint-disable-next-line */
import db from './db';
// Define Schema method= mongoose;
const { Schema } = mongoose;
const CommentSchema = new Schema({
id: {
type: String,
required: true,
unique: true,
},
author_id: {
type: String,
required: true,
},
content: {
type: String,
},
creation_date: {
type: Date,
default: Date.now,
},
interesting_comment: [String],
updated_content_list: [{ previous_date: Date, previous_content: String }],
children: [String],
});
export default mongoose.model('Comment', CommentSchema);
Note: children is about the response to a parent comment, here is the example:
{
"_id" : ObjectId("60217951f57f24079f885d66"),
"interesting_comment" : [
"6ff10e9"
],
"children" : [
"c13e5487-07ba-4bc9-996e-ef1c8f826b32"
],
"updated_content_list" : [ ],
"id" : "6f169ee4-d22d-49a2-9f71-5dacadecf6bb",
"author_id" : "b08a3310-b3f4-4521-9b1a-2d5667a3ea1d",
"content" : "Hello wijdene",
"creation_date" : ISODate("2021-02-08T17:48:01.026Z"),
"__v" : 4
}
{
"_id" : ObjectId("602179d1f57f24079f885d68"),
"interesting_comment" : [ ],
"children" : [ ],
"updated_content_list" : [ ],
"id" : "c13e5487-07ba-4bc9-996e-ef1c8f826b32",
"author_id" : "111",
"content" : "hi nesrine",
"creation_date" : ISODate("2021-02-08T17:50:09.075Z"),
"__v" : 0
}
I implement this function:
async function ListComment() {
const comments = await Comment.find();
return comments;
}
I want to get all the children by their parent comment, I spend hours and I don't get the idea any help please
I try to fix this problem with lookup:
async function ListComment() {
const comments = await Comment.aggregate([{$unwind:{path:"$children",preserveNullAndEmptyArrays: true}},{$lookup:{from:"comments",localField:"children",foreignField:"id",as:"children"}}]);
return comments;
}
But even the child, it is shown in this way. In fact, I add preserveNullAndEmptyArrays: true to preserve parent which doesn't contain a child. But what I get is the new combination + parent without children+children. I want to remove children, any idea
I have four collections person , other_details, occupation_details, bank_details as stated below
person =>[
{
id : 1,
name : 'john',
other_details : 1023
},
{
id : 2,
name : 'mark',
other_details : 99
}
]
other_details => [
{
id: 1023,
married: false,
occupation_details: 144,
bank_details : 10
},
{
id: 99,
married: true,
occupation_details: 45,
bank_details : 11
}
]
occupation_details => [
{
id: 144,
comp_name : 'oscorp inc.'
},
{
id: 45,
comp_name : 'tesla inc.'
}
]
bank_details => [
{
id: 10,
bank : 'Bank of canada'
},
{
id: 11,
bank : 'Peoples bank of canada'
}
]
I am using mongoose library with nodejs
// id = 1
person.findById(id).populate({
path: 'other_details',
populate: [
{
path: 'occupation_details'
},
{
path: 'bank_details'
}
]
})
So the result for the above query comes like below
=>
{
id : 1,
name : 'john',
other_details : {
id: 1023,
married: false,
occupation_details: {
id: 144,
comp_name : 'oscorp inc.'
},
bank_details : {
id: 10,
bank : 'Bank of canada'
}
}
}
But for some reasons I want the result like below
{
id : 1,
name : 'john',
other_details : {
id: 1023,
married: false,
occupation_details: {
id: 144,
comp_name : 'oscorp inc.'
},
bank_details : 10,
custom_bank_details : {
id: 10,
bank : 'Bank of canada'
}
}
}
The change I need is the following, The bank_details object should exist with id and the populated bank_details data from other collection should come in other object name as custom_bank_details
bank_details : 10,
custom_bank_details : {
id: 10,
bank : 'Bank of canada'
}
Update:
You could use virtual to populate bank details into a new field. Something like
OtherDetailsSchema.virtual('custom_bank_details', {
ref: 'BankDetails',
localField: 'bank_details',
foreignField: '_id',
justOne: true
});
Person.findById(id).populate({
path: 'other_details',
populate: [
{path: 'occupation_details'},
{path: 'custom_bank_details'}
]})
Original
I'm not a mongoose user so I'm not sure if it is possible to populate to new field name. If feasible you could quite easily achieve using aggregate with lookup.
Something like
person.aggregate([
{"$lookup":{
"from":"other_details",
"let":{"other_details":"$other_details"},
"pipeline":[
{"$match":{"$expr":{"$eq":["$id","$$other_details"]}}},
{"$lookup":{
"from":"occupation_details",
"localField":"occupation_details",
"foreignField":"id",
"as":"occupation_details"
}},
{"$unwind":"$occupation_details"},
{"$lookup":{
"from":"bank_details",
"localField":"bank_details",
"foreignField":"id",
"as":"custom_bank_details"
}},
{"$unwind":"$custom_bank_details"},
],
"as":"other_details"
}},
{"$unwind":"$other_details"}
])
Working example https://mongoplayground.net/p/5Kee0tBQmTd
I have this record
{
"_id" : ObjectId("5dfdff479ad032cbbc673507"),
"selection" : [
{
"highlights" : "test",
"comment" : "CHANGE THIS",
"el" : "body:nth-child(2)>div:nth-child(2)#root>div.App>p:nth-child(1)"
},
{
"highlights" : "Barrett’s lyrical prose opens with a clever and tender solution",
"comment" : "",
"el" : "body:nth-child(2)>div:nth-child(2)#root>div.App>p:nth-child(2)"
}
],
"category" : [],
"status" : "",
"url" : "http://localhost:3000/theone",
"title" : "React App test",
"__v" : 4
}
And I want to update the comment. I have tried to use update and findOneAndUpdate and nothing is working. Here is my attempt
WebHighlight.findOneAndUpdate(
{
_id: req.params.highlight,
"selection.highlights": "test"
},
{ "selection.$.comment": "yourValue" }
);
That req.params.highlight is the id (I even hardcoded it)
I also tried this
WebHighlight.findById(req.params.highlight, (err, book) => {
var test = [...book.selection];
test[0].comment = "somethibf"
book.save();
res.json(book);
});
And nothing is working.
This is the model
const webhighlightsModel = new Schema({
selection: { type: Array, default: "" },
category: { type: Array, default: [] },
title: { type: String },
url: { type: String },
status: { type: String, default: "" }
});
Actually your code seems to work, but findOneAndUpdate returns the old document if you don't give {new: true} option.
I think for this reason, you think the update wasn't successfull, but if you check your collection, you will see the update.
WebHighlight.findOneAndUpdate(
{
_id: req.params.highlight,
"selection.highlights": "test"
},
{ "selection.$.comment": "yourValue" },
{ new: true }
)
.then(doc => res.send(doc))
.catch(err => res.status(500).send(err));
Also I think it would be better if selection had a sub schema like this:
const mongoose = require("mongoose");
const schema = new mongoose.Schema({
selection: [
new mongoose.Schema({
highlights: String,
comment: String,
el: String
})
],
category: { type: Array, default: [] },
title: { type: String },
url: { type: String },
status: { type: String, default: "" }
});
module.exports = mongoose.model("WebHighlight", schema);
So with this every selection would an _id field, and it would be better to update with this _id.
You should use the $set operator to update existing values:
WebHighlight.findOneAndUpdate(
{
_id: req.params.highlight,
"selection.highlights": "test"
},
{ '$set': { "selection.$.comment": "yourValue" } }
);
Hi,
I have two combo boxes. The value of second combo box depends on first combo select. The user does select the first combo then the store of second will be set accordingly.
Here are my two Combos:
Combo 1
items:[
{
xtype : 'combo',
name : 'cmbSATopFacility',
labelStyle : 'color: black; font-weight: bold; width: 250px; padding: 10;',
labelSeparator : "",
id : 'cmbSATopFacility',
width : 250,
fieldLabel : 'Top MGMT Entity',
triggerAction : 'all',
store : Ext
.create(
'Ext.data.Store',
{
id : 'store',
fields : [
{
name : 'id',
type : 'integer',
},
{
name : 'name'
} ],
remoteGroup : true,
remoteSort : true,
proxy : {
type : 'rest',
url : 'pmsRest/facilities?sub_facility_id=-3',
reader : {
root : "facilityMaster",
idProperty : 'id'
}
},
autoLoad : true
}),
displayField : 'name',
valueField : 'id',
multiSelect : false,
typeAhead : true,
listeners : {
change : function(combo) {
/// code to convert GMT String to date object
n();
Ext.getCmp('cmbSAMedFacility').getStore().load();
}
},
allowBlank : false,
//enableKeyEvents : true,
},
Combo 2
{
xtype : 'combo',
name : 'cmbSAMedFacility',
labelStyle : 'color:black;font-weight:bold;width:250px;padding:10;',
labelSeparator : "",
id : 'cmbSAMedFacility',
width : 250,
fieldLabel : 'Institution',
triggerAction : 'all',
store : medfacility,
displayField : 'name',
valueField : 'id',
multiSelect : false,
typeAhead : true,
//disabled: true,
listeners : {
click : function(combo) {
alert("hjdfhcsdj");
n();
Ext.getCmp(this).getStore().load();
}
},
allowBlank : false,
//enableKeyEvents : true,
},
]
Code to set store
var medfacility = loadFacility();
function loadFacility(){
topApp = Ext.getCmp('cmbSATopFacility').getValue( );
alert(topApp);
var urL = 'pmsRest/facilities?sub_facility_id='+topApp ;
alert(urL);
var store = Ext.create('Ext.data.Store', {
id : 'store',
fields : [
{
name : 'id',
type : 'integer',
},
{
name : 'name'
} ],
remoteGroup : true,
remoteSort : true,
proxy : {
type : 'rest',
url : urL,
reader : {
root : "facilityMaster",
idProperty : 'id'
}
},
autoLoad : true
});
return store;
}
I tried to get the values in the second combo but it didn´t work.
WE CAN USE ONLY
listeners : { change : function(combo) { Ext.getCmp('cmbSAMedFacility').bindStore(n());}},
I think you need describe a store for a second combobox, but without data (empty array).
And fill data for that store when you need by using loadData method.
Hope this helps.