i am new to mongo db.
I am trying to render my toyota car manufacturer alone.
written mongo db query code but its not producing results.
var cursor = db.collection('user-data').find( { carManufacturer: { $eq: toyota } } );
can you guys tell me how to fix it providing my code below
router.get('/cars', function(req, res, next) {
console.log("kumari5");
res.render('cars.hbs');
var toyota = [];
mongo.connect(url, function(err, db) {
assert.equal(null, err);
var cursor = db.collection('user-data').find( { carManufacturer: { $eq: toyota } } );
cursor.forEach(function(doc, err) {
assert.equal(null, err);
toyota.push(doc);
}, function() {
db.close();
res.render('data', {items: toyota});
console.log(toyota);
});
});
});
{
"_id": ObjectId("590a2495bd1d3a356074d36e"),
"DateBough": "21",
"Owner": "Female",
"carManufacturer": ["toyota", "19"],
"Expiry": null
}
{
"_id": ObjectId("347834783478873478788734"),
"DateBough": "21",
"Owner": "Female",
"carManufacturer": ["bmw", "19"],
"Expiry": null
}
{
"_id": ObjectId("34634738468299221182338989"),
"DateBough": "21",
"Owner": "Female",
"carManufacturer": ["benz", "19"],
"Expiry": null
}
{
"_id": ObjectId("47347347834783487437834734"),
"DateBough": "21",
"Owner": "Female",
"carManufacturer": ["toyota", "19"],
"Expiry": null
}
Related
I need to delete a location object from the locations array. It is deeply nested. I followed mongoose documentation but my attempts didn't work:
lists = [{
"listName": "Test",
"_id": "8d55f0afe545a0178c320706",
"listId": "5fd9a3bef6c39b2f9c4df65b",
"date": "12/15/2020",
"dueDate": "2020-11-18",
"items": [
{
"itemNumber": 123,
"description": "item123",
"onHand": 60,
"_id": "13dd1f26ecd2baeb61b3b455",
"locations": [
{
"locationName": "loc1",
"count": 10,
"_id": "50a2c969465ba8010bd48977"
},
{
"locationName": "loc2",
"count": 20,
"_id": "51c2f1d25311dc8fabdbf604a59b"
},
{
"locationName": "Loc3",
"count": 30,
"_id": "7cb0c1f51a91c384846d65f8b2ae"
}
]
},
{more lists}
Attempt:
router.post("/lists/deleteLoc", (req, res) => {
const {
listId,
list_id,
item_id,
location_id
} = req.body;
List.updateOne({
"lists.listId": listId,
"lists._id": list_id
}, {
$pull: {
"lists.$.items": {
locations: {
$elemMatch: {
_id: location_id
})
.then(() => res.json({
msg: "location removed"
}))
.catch((err) => res.status(400).json({
msg: "Error: " + err
}));
});
If the request location_id was "7cb0c1f51a91c384846d65f8b2ae" it should delete the last location from the array. The desired result:
lists = [{
"listName": "Test",
"_id": "8d55f0afe545a0178c320706",
"listId": "5fd9a3bef6c39b2f9c4df65b",
"date": "12/15/2020",
"dueDate": "2020-11-18",
"items": [
{
"itemNumber": 123,
"description": "item123",
"onHand": 60,
"_id": "13dd1f26ecd2baeb61b3b455",
"locations": [
{
"locationName": "loc1",
"count": 10,
"_id": "50a2c969465ba8010bd48977"
},
{
"locationName": "loc2",
"count": 20,
"_id": "51c2f1d25311dc8fabdbf604a59b"
}
]
},
{more lists}
I've tried basically all variations of this, but none have worked.
I'm also not sure if making a router.post or an axios.post request for deletion is correct. Should this be axios.delete and router.delete?
I've tried this in one of my similar DB and worked!
List.updateOne({ "listId": yourListId },
{
'$pull': {
'items.$[item].locations': { "_id": yourLocationId }
}
}, {
"arrayFilters": [
{
"item._id": yourItemId
}
]
}, function (err) {
if (err) {
res.json(err)
} else {
res.json({ message: "Updated" })
}
})
}
You've to put the values that're inside your DB from the object that you want to delete.
So if you want to delete the object with
"locationname" : "Loc3"
You should use
var yourListId = "5fd9a3bef6c39b2f9c4df65b";
var yourItemId = "13dd1f26ecd2baeb61b3b455";
var yourLocationId = "7cb0c1f51a91c384846d65f8b2ae";
Try it out!
For each post I have this structure:
{
"_id": "5dfd3b918937d40b98afd3f8",
"user": "5deea38cfc84f42590e01942",
"title": "test",
"description": "description test",
"category":
{
"0": "1",
"1": "101"
},
"phone": "+1",
"country": "USA",
"city": "NY",
"options": {
"transaction_type": ""
},
"date": "2019-12-20T21:22:25.940Z",
}
In express I using bottom code for find posts by category id but not working what I should to do?
router.get("/category/:category", async (req, res) => {
try {
const posts = await Post.find({
category: { $all: req.params.category }
}).sort({ date: -1 });
if (!posts) {
return res.status(404).json({ msg: "Ads not found" });
}
const resultPosts = posts.slice(req.query.start, req.query.count);
res.json(resultPosts);
} catch (err) {
console.error(err.message);
if (err.kind === "ObjectId") {
return res.status(404).json({ msg: "Ads not found" });
}
res.status(500).send("Server Error!");
}
});
The repo: https://github.com/leongaban/api-design-node/tree/master
My Postman collection: https://www.getpostman.com/collections/b5a03b07836ad34b7758
Expected:
Current "lion" characters:
[
{
"id": "1",
"name": "Teemo",
"pride": "LoL",
"age": "1",
"gender": "male"
},
{
"id": "2",
"name": "Nasus",
"pride": "LoL",
"age": "10",
"gender": "male"
}
]
PUT http://localhost:3000/lions/1
The body:
{
"age": "1",
"gender": "female",
"name": "LuLu",
"pride": "LoL"
}
Should return this new list on GET all lions:
[
{
"id": "1",
"name": "LuLu",
"pride": "LoL",
"age": "1",
"gender": "female"
},
{
"id": "2",
"name": "Nasus",
"pride": "LoL",
"age": "10",
"gender": "male"
}
]
Results
[
{
"id": "2",
"name": "Nasus",
"pride": "2",
"age": "2",
"gender": "female"
},
{
"0": { // <-- This should not be here
"id": "1",
"name": "Teemo",
"pride": "1",
"age": "1",
"gender": "female"
},
"age": "1",
"gender": "female",
"name": "LuLu",
"pride": "LoL"
}
]
Full server.js
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const path = require('path')
const port = 3000
app.use(express.static('client'))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
let lions = []
let id = 0
app.get('/lions', function(req, res) {
console.log('GET lions:', lions)
res.json(lions)
})
app.get('/lions/:id', function(req, res) {
let lion = lions.filter((lion => lion.id === req.params.id))
res.json(lion || {})
})
app.post('/lions', function(req, res) {
id++
const lion = Object.assign({ id: id.toString() }, req.body)
lions.push(lion)
res.json(lion)
});
app.put('/lions/:id', function(req, res) {
const paramId = req.params.id
const updated = req.body
if (updated.id) {
delete updated.id
}
const oldLion = lions.filter((lion => lion.id === paramId))
if (!oldLion) {
res.send()
}
const newLion = Object.assign(updated, oldLion)
console.log('newLion', newLion)
lions = lions.filter(lion => lion.id !== paramId)
lions.push(newLion)
res.json(newLion)
});
app.listen(port, () => console.log(`NODE RUNNING on port: ${port}`))
The PUT function
app.put('/lions/:id', function(req, res) {
const paramId = req.params.id
const updated = req.body
if (updated.id) {
delete updated.id
}
// Here I find the oldLion to replace by id:
const oldLion = lions.filter((lion => lion.id === paramId))
if (!oldLion) {
res.send()
}
// Here I create a new object for the new "lion":
const newLion = Object.assign(updated, oldLion)
console.log('newLion', newLion)
// Here I filter out the old lion:
lions = lions.filter(lion => lion.id !== paramId)
// New lion is pushed in:
lions.push(newLion)
res.json(newLion)
});
One potential issue that can be on the app.put() method, is that when you do const oldLion = lions.filter((lion => lion.id === paramId)) you will get an array as result. Check Array.filter() for more info about this. So, I believe you want to use Array.find() instead of the filter() because later you are calling:
const newLion = Object.assign(updated, oldLion);
And, if oldLion is an array, numeric-properties will be added to the updated object, as you can see on next example:
const updated = {somekey: "somevalue"};
console.log(Object.assign(updated, [{somekey: "updatedValue"}]));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
So, this is generating your unexpected structure, as you have mentioned:
[
{
"id": "2",
"name": "Nasus",
"pride": "2",
"age": "2",
"gender": "female"
},
{
"0": { // <-- This should not be here
"id": "1",
"name": "Teemo",
"pride": "1",
"age": "1",
"gender": "female"
},
"age": "1",
"gender": "female",
"name": "LuLu",
"pride": "LoL"
}
]
UPDATE
However, after reading your other fix commented, and understanding what you are trying to do, maybe it is better to use Array.findIndex() and write your put() method like this:
app.put('/lions/:id', function(req, res)
{
const paramId = req.params.id;
const updated = req.body;
if (updated.id)
delete updated.id;
// Here I find the oldLion to replace by id:
const oldLionIdx = lions.findIndex(lion => lion.id === paramId);
if (oldLionIdx < 0)
res.send();
// Here I update the object with the new "lion" properties:
const newLion = Object.assign(lions[oldLionIdx], updated);
console.log('newLion', newLion);
res.json(newLion);
});
I am trying to find an update a document using mongoose, by removing an object from a nested array. My target document is the following:
user = {
"userId" : "myId",
"connections":
[{
"dateConnectedUnix": 1334567891,
"isActive": true,
"sessions": [
{"device": "mobile", "country": "US"},
{"device": "desktop", "country": "US"}
]
}, {
"dateConnectedUnix": 1334567893,
"isActive": false,
"sessions": [
{"device": "mobile", "country": "CA"},
{"device": "desktop", "country": "CA"}
]
}]
}
here is my attempt, but it is not updating the document:
Users.findOneAndUpdate({ "userId": "myId", "connections.dateConnectedUnix": 1334567891 },
{ $pull: { sessions: { device: "mobile" } } }, (err) => {
if (err) {
return res.status(404).json({ message: 'Error' });
}
return res.status(200).json({
success: true,
message: 'success'
});
}
);
the resulting document should look like:
user = {
"userId" : "myId",
"connections":
[{
"dateConnectedUnix": 1334567891,
"isActive": true,
"sessions": [
{"device": "desktop", "country": "US"}
]
}, {
"dateConnectedUnix": 1334567893,
"isActive": false,
"sessions": [
{"device": "mobile", "country": "CA"},
{"device": "desktop", "country": "CA"}
]
}]
}
basically it is finding the user by the id, and then finding the connection by date, and then removing the device if mobile. In my particular case, the result is always one matching document and one matching connection and one matching session.
Because your sessions array is inside connections
Try "connections.$.sessions" instead of sessions so your query would be
Users.findOneAndUpdate({ "userId": "myId", "connections.dateConnectedUnix": 1334567891 },
{ $pull: { "connections.$.sessions" : { device: "mobile" } } }, (err) => {
if (err) {
return res.status(404).json({ message: 'Error' });
}
return res.status(200).json({
success: true,
message: 'success'
});
}
);
Users.findOneAndUpdate({ _id: "myId" }, { $pull: { connections.sessions: { device: "mobile" } } }, { new: true });
It seems I can't parse my JSON data from Parse into my web app. When I try alert my JSON data, it shows like this
[{
"address1": "Test",
"address2": "Test",
"bathroom": "1",
"bedroom": "1",
"builtUpArea": "123",
"cityId": "1",
"countryId": "1",
"description": "Test",
"exclusive": true,
"facingDirectionId": "1",
"floorlevel": "1",
"furnishTypeId": "1",
"landArea": "123",
"landAreaTypeId": "1",
"name": "Test",
"ownerContact": "Test",
"ownerEmail": "Test",
"ownerIc": "Test",
"ownerName": "Test",
"poscode": "123",
"price": "Test",
"purchaserId": "xZyLAKnCnXt",
"remark": "Test",
"stateId": "1",
"statusId": "1",
"tenureId": "1",
"typeId": "1",
"user": {
"__type": "Pointer",
"className": "_User",
"objectId": "rquoctPnNz"
},
"objectId": "0nfSPUwgvm",
"createdAt": "2015-04-10T02:16:54.509Z",
"updatedAt": "2015-04-10T02:16:54.509Z"
}]
But nothing appear in my view page, only createdAt and updatedAt with "" symbol.
My code:
JavaScript:
var Property = Parse.Object.extend("Property");
var user = Parse.User.current();
var query = new Parse.Query(Property);
query.equalTo("user", user);
query.find({
success: function(data) {
alert(JSON.stringify(data));
$scope.properties = data;
},
error: function(object, error) {
alert(JSON.stringify(error));
}
});
HTML:
<tr ng-repeat="property in properties | filter:query">
<td>{{property.name}}</td>
<td>RM {{property.price}}</td>
<td>{{property.createdAt}}</td>
<td>{{property.updatedAt}}</td>
</tr>
I already found the answer.
$scope.properties = [];
var Property = Parse.Object.extend("Property");
var user = Parse.User.current();
var query = new Parse.Query(Property);
query.equalTo("user", user);
query.find({
success: function(data) {
var index = 0;
var Arrlen = results.length;
for (index = 0; index < Arrlen; ++index) {
var obj = results[index];
$scope.properties.push({
objectId: obj.attributes.objectId,
name: obj.attributes.name,
price: obj.attributes.price,
createdAt: obj.createdAt,
updatedAt: obj.updatedAt
});
}
},
error: function(object, error) {
alert(JSON.stringify(error));
}
});