I am trying to display order data from a nested mongoose object and I can't seem to get the data to display correctly. Appreciate all help in advance.
Here is the order model:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var schema = new Schema({
//todo: check the user part in this model
user: {type: Schema.Types.ObjectId, ref: 'User'},
cart: {type: Object, required: true},
address: {type: String, required: true},
name: {type: String, required: true},
paymentId: {type: String, required: true},
email:{type: String, required: true},
time : { type : Date, default: Date.now }
});
module.exports = mongoose.model('Order', schema);
Here is how the data is saved to the database:
{ "_id" : ObjectId("5975214fc8db300731d0e8b8"), "user" : ObjectId("5951d4d1f57b440556898e1a"), "cart" : { "items" : { "596068
4581c02d077c914283" : { "item" : { "_id" : "5960684581c02d077c914283", "imagePath" : "https://www.swarovski.com/is-bin/inters
hop.static/WFS/SCO-Media-Site/-/-/publicimages//CG/B2C/PROD/180/Swarovski-Cosmic-Bracelet-5226308-W180.jpg", "title" : "Brace
let 1", "description" : "This is the first Bracelet in the collection.", "price" : 10, "__v" : 0 }, "qty" : 1, "price" : 10 }
, "59742cad8f1bf6071b5419cb" : { "item" : { "_id" : "59742cad8f1bf6071b5419cb", "title" : "Bracelet 2 ", "imagePath" : "https
://img0.etsystatic.com/160/0/12655872/il_340x270.1187191078_i2ha.jpg", "description" : "This is the second Bracelet in the co
llection.", "price" : 5, "__v" : 0 }, "qty" : 1, "price" : 5 }, "59742ebdd1242f07530d2b30" : { "item" : { "_id" : "59742ebdd1
242f07530d2b30", "title" : "Bracelet 3", "imagePath" : "https://www.costco.com/wcsstore/CostcoUSBCCatalogAssetStore/category-
tiles/pearl-bracelets.jpg", "description" : "This is the third Bracelet in the collection.", "price" : 12, "__v" : 0 }, "qty"
: 1, "price" : 12 } }, "totalQty" : 3, "totalPrice" : 27 }, "address" : "6210 place", "name" : "pauls", "paymentId" : "ch_1A
isRfDfJryYeuMpbJGWY2NV", "email" : "pauls#a.com", "time" : ISODate("2017-07-23T22:21:03.819Z"), "__v" : 0 }
I would like to display the data in a table using ejs:
<table border="1">
<tr>
<th>Item</th>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<% orders.forEach(function(order){ %>
<tr>
<td><%=...item%> </td>
<td><%=...description%> </td>
<td><%=...price%> </td>
<td><%=...quantity%> </td>
</tr>
<% }); %>
</table>
Here is the route:
router.get('/order', function(req, res){
Order.find({}, function(err, allOrders){
if(err){
console.log(err);
} else {
res.render("admin/order", {orders: allOrders});
}
});
});
Here is the cart:
module.exports = function Cart(oldCart) {
this.items = oldCart.items || {};
this.totalQty = oldCart.totalQty || 0;
this.totalPrice = oldCart.totalPrice || 0;
this.add = function (item, id) {
var storedItem = this.items[id];
if (!storedItem) {
storedItem = this.items[id] = {item: item, qty: 0, price: 0};
}
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
this.totalQty++;
this.totalPrice += storedItem.item.price;
};
this.reduceByOne = function (id) {
this.items[id].qty--;
this.items[id].price -= this.items[id].item.price;
this.totalQty--;
this.totalPrice -= this.items[id].item.price;
if (this.items[id].qty <=0) {
delete this.items[id];
}
};
this.removeItem = function (id) {
this.totalQty -= this.items[id].qty;
this.totalPrice -= this.items[id].price;
delete this.items[id];
};
this.generateArray = function () {
var arr = [];
for (var id in this.items) {
arr.push(this.items[id]);
}
return arr;
};
};
Edit: Now data is saved like below:
{ "_id" : ObjectId("5976b6b11306910658b1ff57"), "address" : "6210 place", "name" : "frank", "paymentId" : "ch_1AjJRVDfJ
ryYeuMpJC80cp5k", "email" : "g#mail.com", "time" : ISODate("2017-07-25T03:10:41.522Z"), "cart" : [ { "items" : { "59752
28a215c0f074b64f58e" : { "item" : { "_id" : "5975228a215c0f074b64f58e", "title" : "Bracelet 3", "imagePath" : "https://
www.costco.com/wcsstore/CostcoUSBCCatalogAssetStore/category-tiles/pearl-bracelets.jpg", "description" : "This is brace
let 3", "price" : 12, "__v" : 0 }, "qty" : 1, "price" : 12 }, "59752242215c0f074b64f58c" : { "item" : { "_id" : "597522
42215c0f074b64f58c", "title" : "Bracelet 1", "imagePath" : "https://img0.etsystatic.com/160/0/12655872/il_340x270.11871
91078_i2ha.jpg", "description" : "This is bracelet 1", "price" : 10, "__v" : 0 }, "qty" : 2, "price" : 20 }, "5975226a2
15c0f074b64f58d" : { "item" : { "_id" : "5975226a215c0f074b64f58d", "title" : "Bracelet 2", "imagePath" : "http://media
.tiffany.com/is/image/Tiffany/EcomBrowseM/paloma-picasso-knot-bead-bracelet-34946183_963148_ED.jpg?op_usm=1.00,1.00,6.0
0&defaultImage=NoImageAvailable&&", "description" : "This is bracelet 2", "price" : 5, "__v" : 0 }, "qty" : 1, "price"
: 5 } }, "totalQty" : 4, "totalPrice" : 37 } ], "__v" : 0 }
Related
I want to get all category name and total record with respect to category object id.
I am new in Node JS and want to create api for listing and total record with respective object id.
My json for Categgory is -
/* 1 createdAt:8/21/2019, 3:00:35 PM*/
{
"_id" : ObjectId("5d5d0f3b3dff690eac4872ee"),
"isForHomePage" : false,
"isactive" : false,
"name" : "Welcome",
"description" : "Solutions for Your Business",
"catImage" : "http://localhost:3000/static/media/software-service.1ec2246b.jpg",
"createdTime" : 1566379835,
"__v" : 0
},
/* 2 createdAt:8/19/2019, 12:17:45 PM*/
{
"_id" : ObjectId("5d5a4611eb5bc029d4463406"),
"isForHomePage" : true,
"isactive" : false,
"name" : "Test",
"description" : "Solutions for Your Business",
"catImage" : "http://localhost:3000/static/media/software-service.1ec2246b.jpg",
"createdTime" : 1566197265,
"__v" : 0
},
/* 3 createdAt:8/19/2019, 12:10:01 PM*/
{
"_id" : ObjectId("5d5a44417d10952b50ff13a0"),
"isForHomePage" : true,
"isactive" : true,
"name" : "Software Services",
"description" : "Solutions for Your Business",
"catImage" : "http://localhost:3000/static/media/software-service.1ec2246b.jpg",
"createdTime" : 1566196801,
"__v" : 0
},
/* 4 createdAt:8/19/2019, 12:07:51 PM*/
{
"_id" : ObjectId("5d5a43bf7d10952b50ff139f"),
"isForHomePage" : true,
"isactive" : true,
"name" : "Analytics",
"description" : "Solutions for Your Business",
"catImage" : "http://localhost:3000/static/media/analytics.cf89d7fe.jpg",
"createdTime" : 1566196671,
"__v" : 0
}
and JSON for jobs is -
/* 1 createdAt:8/22/2019, 12:48:08 PM*/
{
"_id" : ObjectId("5d5e41b0807a2504e15dcc01"),
"status" : 8001,
"duration" : 10,
"isactive" : true,
"userWhoCreated" : ObjectId("5d5d40276ab29a4daef653ae"),
"companyNane" : "Sanganan It Solutions Pvt. Ltd.",
"contactPerson" : "Gaurav Sinha",
"jobTitle" : "iOS Developer",
"category" : ObjectId("5d5a4611eb5bc029d4463406"),
"description" : "iOS Developer lead requirement",
"descriptionLink" : "www.abc.com",
"createdTime" : 1566458288,
"__v" : 0
},
/* 2 createdAt:8/22/2019, 12:17:31 PM*/
{
"_id" : ObjectId("5d5e3a83979672041fee4d0a"),
"status" : 8002,
"duration" : 10,
"isactive" : true,
"userWhoCreated" : ObjectId("5d5d40276ab29a4daef653ae"),
"companyNane" : "Sanganan It Solutions Pvt. Ltd.",
"contactPerson" : "Gaurav Sinha",
"jobTitle" : "iOS Developer",
"category" : ObjectId("5d5a4611eb5bc029d4463406"),
"description" : "iOS Developer lead requirement",
"descriptionLink" : "www.abc.com",
"createdTime" : 1566456451,
"__v" : 0
}
We have category json and category object id is present in jobs json. Like Test category from Category JSON has two jobs in JOB JSON.
I have tried this solution -
router.get("/getAllCategory", function (req, res) {
categoryObj.find({ 'isactive': true }, function (err, CategoryList) {
if (err) {
var message = { "Success": 0, "Message": "Some error found" };
res.send(message)
}
else {
var message = { "Success": 1, "Category": CategoryList };
res.send(message)
}
})
});
but it is giving me list of categories not count.
my expected output json must be like this -
[
{
'categoryname': 'Analytics',
'totalJobsOfThisCategory':'0'
},
{
'categoryname': 'Software Services',
'totalJobsOfThisCategory':'0'
},
{
'categoryname': 'Test',
'totalJobsOfThisCategory':'2'
},
]
Use aggregate function of mongodb
db.jobs.aggregate([
{ $group: { _id: "$category", total: { $sum: 1 } } }
])
Use populate
const x= await X.find()
.populate('userWhoCreated', 'field1 field2')
.populate('category', 'field1 field2');
res.json({
x,
});
I have a schema where I need to perform a search in array of objects. I have tried many ways but it doesn't seems to work. Below is my code.
let productsSchema = new mongooseSchema({
productId: {type: mongooseSchema.Types.ObjectId, ref: 'Product'},
mainAttributes: [{
subCategoryId: {type: mongooseSchema.Types.ObjectId, ref: 'CategorySubCategory'},
attributes: Object
}],
createdAt: Date,
updatedAt: Date
})
productsSchema.index({'mainAttributes': 'text'})
let attributes = mongoose.model('Attributes', productsSchema);
let results = await CategorySubCategory.attributes.find({"$text": {"$search": req.body.searchText}})
Currently below record is saved in mongodb
{
"_id" : ObjectId("5bba1b39ad9387431f9f5fd9"),
"productId" : ObjectId("5bba1b397d90713320c441f8"),
"__v" : 0,
"createdAt" : ISODate("2018-10-07T14:42:01.723Z"),
"mainAttributes" : [
{
"_id" : ObjectId("5bba1b397d90713320c441f9"),
"subCategoryId" : ObjectId("5bba1b397d90713320c441f7"),
"attributes" : {
"title" : {
"text" : "some title",
"type" : "text"
}
"state" : {
"text" : "California",
"type" : "text"
},
"city" : {
"text" : "San Francisco",
"type" : "text"
}
}
},
{
"_id" : ObjectId("5bba1b397d90713320c441fb"),
"subCategoryId" : ObjectId("5bba1b397d90713320c441fa"),
"attributes" : {
"temprature" : {
"degree" : "20C",
"type" : "text"
}
}
}
],
"updatedAt" : ISODate("2018-10-07T14:42:01.723Z")
}
I need to perform a search on the basis of text, e.g. when I give San, it should return me the result, but it returns empty.
I have figured it out what was the problem,
I need to explicitly remove an index, and then added
productsSchema.index({'$**': 'text'}) to make it work
Below is my update code:
async.each(jsondata,
function(itemdata, callbackNew){
itemdata.store_code=parseInt(itemdata.store_code);
//console.log(itemdata.store_code);
db.mdb.collection('counters')
.update(
{"store_code": itemdata.store_code},{$set:itemdata},
{ upsert: true },
function (erreach, data) {
if (erreach) {
console.log("error reported")
console.log(erreach)
callbackNew(erreach);
}
else{
//console.log('Data updated')
callbackNew();
app.send(req,res,data);
}
})
},function(err){
if(err) {
//console.log("this is the error"+err)
app.senderr(req,res,err);
}
else{
app.send(req,res,jsondata);
}
});
But the DB is not getting changed.The values are same before and after updation.
Below is the JSON of my database.
{
"_id" : ObjectId("586aac4c8231ee0b98458045"),
"store_code" : NumberInt(10800),
"counter_name" : "R.N.Electric",
"address" : "314 khatipura road",
"locality" : "Khatipura Road (Jhotwara)",
"pincode" : "302012",
"town" : "JAIPUR",
"gtm_city" : "JAIPUR",
"sales_office" : "URAJ",
"owner_name" : "Rajeev",
"owner_mobile" : "9828024073",
"division_mapping" : [
{
"dvcode" : "cfc",
"dc" : "trade",
"beatcode" : "govindpura",
"fos" : {
"_id" : ObjectId("586ab8318231ee0b98458843"),
"loginid" : "9928483483",
"name" : "Arpit Gupta",
"division" : [
"cfc",
"iron"
],
"sales_office" : "URAJ",
"gtm_city" : "JAIPUR"
},
"beat" : {
"_id" : ObjectId("586d372b39f64316b9c3cbd7"),
"division" : {
"_id" : ObjectId("5869f8b639f6430fe4edee2a"),
"clientdvcode" : NumberInt(40),
"code" : "cfc",
"name" : "Cooking & Fabric Care",
"project_code" : "usha-fos",
"client_code" : "usha",
"agent_code" : "v5global"
},
"beatcode" : "govindpura",
"sales_office" : "URAJ",
"gtm_city" : "JAIPUR",
"active" : true,
"agency_code" : "v5global",
"client_code" : "USHA_FOS",
"proj_code" : "usha-fos",
"fos" : {
"_id" : ObjectId("586ab8318231ee0b98458843"),
"loginid" : "9928483483",
"name" : "Arpit Gupta",
"division" : [
"cfc",
"iron"
],
"sales_office" : "URAJ",
"gtm_city" : "JAIPUR"
}
}
}
],
"distributor_mail" : "sunil.todi#yahoo.in",
"project_code" : "usha-fos",
"client_code" : "usha",
"agent_code" : "v5global",
"distributor_name" : "Sundeep Electrical"
}
And below is the document which I am sending in update($set:itemdata):
{ store_code: '10800',
counter_name: 'R.N.Electrics',
address: '314 khatipura road',
locality: 'Khatipura Road (Jhotwara)',
pincode: '302012',
town: 'JAIPUR',
gtm_city: 'JAIPUR',
sales_office: 'URAJ',
owner_name: 'Rajeev',
owner_mobile: '9828024073',
distributor_mail: 'sunil.todi#yahoo.in',
distributor_name: 'Sundeep Electrical' }
I'm very new to MongoDB and mongoose and I'd like to get the total number of subscribers from start date to current date by day. In other words, I need to group all my subscribers by day, and for each day I need to sum all of my previous subscribers.
Here are some of my my documents:
{ "_id" : ObjectId("574cef8ee62502d08f34c075"), "userId" : "a7zd609h54wm5kt", "subscribedAt" : ISODate("2016-05-30T18:22:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.098Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c076"), "userId" : "3q2tvd53zcap5mq", "subscribedAt" : ISODate("2016-05-30T19:52:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.113Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c077"), "userId" : "nvx8mnu1xis5jxt", "subscribedAt" : ISODate("2016-05-28T19:52:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.117Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c078"), "userId" : "l7eedg616r0zbdf", "subscribedAt" : ISODate("2016-05-28T16:28:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.122Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c079"), "userId" : "9r1wl8ao8bls7g7", "subscribedAt" : ISODate("2016-05-28T11:05:05Z"), "isSubscribed" : false, "createdAt" : ISODate("2016-05-31T01:57:34.125Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c07a"), "userId" : "ygwve2e47p7fanl", "subscribedAt" : ISODate("2016-05-29T00:28:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.125Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c07b"), "userId" : "1gxspx9jypwc9tu", "subscribedAt" : ISODate("2016-05-29T19:52:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.127Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c07c"), "userId" : "hvy4xjppos8ch2b", "subscribedAt" : ISODate("2016-05-29T01:36:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.127Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c07d"), "userId" : "bmpql2d7wkl0jnw", "subscribedAt" : ISODate("2016-05-29T21:50:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.127Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c07e"), "userId" : "uir99sy6q3p6i0i", "subscribedAt" : ISODate("2016-05-29T08:22:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.131Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c07f"), "userId" : "qmzn3rz308ku017", "subscribedAt" : ISODate("2016-05-29T22:02:05Z"), "isSubscribed" : false, "createdAt" : ISODate("2016-05-31T01:57:34.132Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c080"), "userId" : "ok46sxaf8urrqtj", "subscribedAt" : ISODate("2016-05-29T07:33:05Z"), "isSubscribed" : false, "createdAt" : ISODate("2016-05-31T01:57:34.132Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c081"), "userId" : "ot4nmxqsn4o98vn", "subscribedAt" : ISODate("2016-05-29T23:52:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.138Z"), "__v" : 0 }
{ "_id" : ObjectId("574cef8ee62502d08f34c082"), "userId" : "2voy5ttkk39i1f0", "subscribedAt" : ISODate("2016-05-30T00:52:05Z"), "isSubscribed" : true, "createdAt" : ISODate("2016-05-31T01:57:34.138Z"), "__v" : 0 }
So I've got 2 subscribers on 2016-05-28, 6 subscribers on 2016-05-29 and 3 subscribers on 2016-05-30,
The result I'm hoping to achieve is something like this
{
"results" : [
{
"date" : ISODate("2016-05-28T00:00:00Z"),
"subscribers" : 2
},
{
"date" : ISODate("2016-05-29T00:00:00Z"),
"subscribers" : 8
},
{
"date" : ISODate("2016-05-30T00:00:00Z"),
"subscribers" : 11
},
]
}
I've tried Aggregation Framework with the following code:
var express = require('express'),
router = express.Router(),
User = require('../models/user');
router.get('/', function(req, res, next) {
User.aggregate([
{
$match: { isSubscribed: true, subscribedAt: {$gte: new Date("2016-05-28T00:00:00+01:00"), $lte: new Date()}}
},
{
$group: {
_id: {$dateToString: { format: "%Y-%m-%d", date: "$subscribedAt" }},
count : { $sum : 1 }
},
},
{
$project: {
_id : 0,
subscribeDate : "$_id",
count : 1
}
},
{
$sort: {subscribeDate: 1}
}
], function(err, result){
if (err) {
console.log("This is an error find the user!")
}
res.render('dashboard', {results: result, title: "Welcome to analytics dashboard!"});
});
});
module.exports = router;
But this only gives me the total subscribers of each day, NOT the the sumup of all the previous subscribers.
{ "count" : 2, "subscribeDate" : "2016-05-28" }
{ "count" : 6, "subscribeDate" : "2016-05-29" }
{ "count" : 3, "subscribeDate" : "2016-05-30" }
I've also tried mapReduce as suggested here with the following code:
var express = require('express'),
router = express.Router(),
User = require('../models/user'),
DailySubscriber = require('../models/dailySubscriber');
router.get('/', function(req, res, next) {
var userObject = {
"query": {isSubscribed: true},
"out": "dailySubscriber"
};
userObject.map = function () {
var date = new Date(this.subscribedAt.valueOf() - (this.subscribedAt.valueOf() % (1000 * 60 * 60 * 24 )));
emit(date, 1)
}
userObject.reduce = function (k, vals) { return vals.length }
User.mapReduce(userObject, function (err, results) {
//console.log(results)
})
var subscriberObject = {
"scope": { "total": 0 },
"finalize": function(key, value) {
total += value;
return total;
},
"out": "totalSubscriber"
};
subscriberObject.map = function () {
emit(this._id, this.value)
}
subscriberObject.reduce = function (k, vals) { return vals.length }
DailySubscriber.mapReduce(subscriberObject, function (err, total) {
console.log("This is the result" + total)
})
res.render('dashboard', {title: "Welcome to analytics dashboard!"});
});
module.exports = router;
This did NOT work when I ran my node app and I got the error This is the result undefined in the console, BUT it did work in MongoDB Shell with the following result which is very close to what I want but still not so ideal, as it always shows _id and value as the key and value.
{
"results" : [
{
"_id" : ISODate("2016-05-28T00:00:00Z"),
"value" : 2
},
{
"_id" : ISODate("2016-05-29T00:00:00Z"),
"value" : 8
},
{
"_id" : ISODate("2016-05-30T00:00:00Z"),
"value" : 11
},
]
}
What would be the best way of doing it? I'm using Node.js, Express and Mongoose, if that helps.
Any help would be much appreciated! Thanks in advance!
imho - having aggregation framework to have a daily sum is best what we can squeeze from mongo. As (from sql world) we don't have CTE, we cannot refer to previous document and that makes some analytics hard.
What I will do in this case is just simple forEach loop and update the sum value creating moving Sum in this particular case. This will require that data need to be sorted from oldest to newest. A sudocode for that below:
var previous = 0;
forEach (var r in result)
{
r.count += previous;
previous = r.count;
}
I am trying to create a simple text search on a combined index.
Here is my mongoose model:
// models/user.js
// load the things we need
var mongoose = require('mongoose');
// define the schema for our user model
var itemSchema = mongoose.Schema({
globalinfo : {
ownerobjectid : String,
name : String,
desc : String,
startdate : Date,
enddate : Date,
price : Number,
status : String,
statuscss : String,
dateadded : Date,
locationline1 : String,
locationline2 : String,
locationline3 : String,
locationtown : String,
locationpostcode : String,
locationlatitude : Number,
locationlongitude : Number,
termsapprove : Boolean,
friendlyurl : String,
itemsearchinfo : String,
}
});
itemSchema.index(
{
"globalinfo.itemsearchinfo": "text",
"globalinfo.name": "text"
}
); // schema level
// create the model for users and expose it to our app
module.exports = mongoose.model('Item', itemSchema);
This is my search query:
Item.find(
{ $text : { $search : "item" } }
).exec(function(err, items) {
The issue is that the query always returns no results!
I have one document in the model:
{
"_id" : ObjectId("56781cb97ae92ff08b55d4f1"),
"globalinfo" : {
"friendlyurl" : "item-a",
"dateadded" : ISODate("2015-12-21T15:37:29.591Z"),
"itemsearchinfo" : "Woop lawn mower for rent!\nYou should use this space to describe the item in detail and make it appealing\nTo the renter write your stuff here.",
"statuscss" : "na",
"status" : "Not Available Yet",
"locationlongitude" : null,
"locationlatitude" : null,
"locationpostcode" : "test",
"locationtown" : "test",
"locationline3" : "",
"locationline2" : "",
"locationline1" : "test",
"termsapprove" : true,
"price" : 3,
"enddate" : ISODate("2015-12-31T00:00:00.000Z"),
"startdate" : ISODate("2015-12-23T00:00:00.000Z"),
"desc" : "\n <h3>woop Lawn Mower for Rent! </h3>\n <p>You should use this space to describe the item in detail and make it appealing to the renter <strong>Write your stuff here.</strong> \n </p>",
"name" : "item A",
"ownerobjectid" : "56781909155232b7871edb17"
},
"__v" : 0
}
The output of db.items.getIndexes():
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "whatplot_local_db.items"
},
{
"v" : 1,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "itemsearchinfo_text_name_text",
"ns" : "whatplot_local_db.items",
"background" : true,
"weights" : {
"itemsearchinfo" : 1,
"name" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 2
}
]
Have you tried re-indexing the collection?
Mongo command:
db.collection.reIndex();
The issue was with the way I was indexing. Using double quotes does not work:
itemSchema.index(
{
"globalinfo.itemsearchinfo": "text",
"globalinfo.name": "text"
}
); // schema level
However single quotes does:
itemSchema.index(
{
'globalinfo.itemsearchinfo': "text",
'globalinfo.name': "text"
}
); // schema level