Mongoskin findAndModify ID object id - mongoskin

Using nodejs, mongoskin.. I'd like to return the updated doc so Im using findAndModify, however the query {_id: "someid"} doesn't work. I think I need to use {id: ObjectID{'someid'} as the query. How do I get the ObjectId type into JS?

try this:
ObjectID = require('mongoskin').ObjectID
{_id: new ObjectID("someid")}

Here is a solution
var mongo = require("mongoskin");
var conn = mongo.db(YOUR_DETAILS);
var BSON = mongo.BSONPure;
this enables you to convert your id int, string or whatever using:
conn.collection(YOUR_COLLECTION).find({_id:new BSON.ObjectID(YOUR_ID)})
Hope that helps!

You can do something like:
yourCollection = db.collections('yourCollection');
Then
{ _id: yourCollection.id("someId") }

Related

How to 'replace' table name in raw SQL query?

I have the following SQL query, which works:
await sequelize.query(
"DELETE FROM `table_name` WHERE (?) IN (?)",
{
replacements: ["project_id", projectIds],
type: QueryTypes.DELETE,
}
);
But I also want to use a replacement for table_name like this:
await sequelize.query(
"DELETE FROM (?) WHERE (?) IN (?)",
{
replacements: ["table_name", "project_id", projectIds],
type: QueryTypes.DELETE,
}
);
But this doesn't work and generates an error about SQL syntax. How can I make this work?
You are mixing data value binding and quoting identifiers.
There is ancient issue in the repo: https://github.com/sequelize/sequelize/issues/4494, which sounds like the problem above.
I believe you can create a workaround that respects different sql dialects like this:
const queryInterface = sequelize.getQueryInterface();
const tableName = queryInterface.quoteIdentifier("projects");
const columnName = queryInterface.quoteIdentifier("project_id");
await sequelize.query(`DELETE FROM ${tableName} WHERE ${columnName} IN (?)`, {
replacements: [project_ids],
type: QueryTypes.DELETE,
});
Assuming you are using sequelize 6.x.

How to delete object with Id in Realm or Primary Key?

I have below object :
obj1 = [{ id = 1, name = "abc"}, {id=2, name="pqr"}, {id=3, name="xyz"}]
I need to delete an object with id=2 where id is Primary Key too.
Below method using to delete the object
const collection = RealmDB.realm
.objects("StudentName")
.filtered(`id= $0`, '65');
RealmDB.realm.write(() => {
RealmDB.realm.delete(collection);
});
But it is not working with id object can anyone please suggest better way to do this ?
But still that object is there so may I know what is wrong here.
const id = 1;
realm.write(()=>{
realm.delete(realm.objectForPrimaryKey('Baby',id));
})
Try this.
Hello resolved an issue by following query with no error
const collection = RealmDB.realm
.objects('StudentName')
.filtered('id= $0', `65`);
RealmDB.realm.write(() => {
RealmDB.realm.delete(collection);
Thank you

Node-postgres: named parameters query (nodejs)

I used to name my parameters in my SQL query when preparing it for practical reasons like in php with PDO.
So can I use named parameters with node-postgres module?
For now, I saw many examples and docs on internet showing queries like so:
client.query("SELECT * FROM foo WHERE id = $1 AND color = $2", [22, 'blue']);
But is this also correct?
client.query("SELECT * FROM foo WHERE id = :id AND color = :color", {id: 22, color: 'blue'});
or this
client.query("SELECT * FROM foo WHERE id = ? AND color = ?", [22, 'blue']);
I'm asking this because of the numbered parameter $n that doesn't help me in the case of queries built dynamically.
There is a library for what you are trying to do. Here's how:
var sql = require('yesql').pg
client.query(sql("SELECT * FROM foo WHERE id = :id AND color = :color")({id: 22, color: 'blue'}));
QueryConvert to the rescue. It will take a parameterized sql string and an object and converts it to pg conforming query config.
type QueryReducerArray = [string, any[], number];
export function queryConvert(parameterizedSql: string, params: Dict<any>) {
const [text, values] = Object.entries(params).reduce(
([sql, array, index], [key, value]) => [sql.replace(`:${key}`, `$${index}`), [...array, value], index + 1] as QueryReducerArray,
[parameterizedSql, [], 1] as QueryReducerArray
);
return { text, values };
}
Usage would be as follows:
client.query(queryConvert("SELECT * FROM foo WHERE id = :id AND color = :color", {id: 22, color: 'blue'}));
Not exactly what the OP is asking for. But you could also use:
import SQL from 'sql-template-strings';
client.query(SQL`SELECT * FROM unicorn WHERE color = ${colorName}`)
It uses tag functions in combination with template literals to embed the values
I have been working with nodejs and postgres. I usually execute queries like this:
client.query("DELETE FROM vehiculo WHERE vehiculo_id= $1", [id], function (err, result){ //Delete a record in de db
if(err){
client.end();//Close de data base conection
//Error code here
}
else{
client.end();
//Some code here
}
});

Retrieving Data in Webmatrix without 'foreach'

I want to retrieve a single item of data from my database to then use as a value for an input element.
Using the below will retrieve each instance of SubmittedBy in the DB so results in multiple results.
var UserId = WebSecurity.CurrentUserId;
var db = Database.Open("testDB");
var selectQueryString = "Select SubmittedBy FROM Posts WHERE UserId=#0";
var data = db.Query(selectQueryString, UserId);
#foreach(var row in data)
{
<input type="email" name="emailfrom" id="emailfrom" value="#SubmittedBy"/>
}
How do I retrieve SubmittedBy so it only gives the one result i.e. without the foreach loop?
Thanks in advance!!!
If by your data restriccions are you going to obtain 1 and only 1 value for an specific UserId, you could use
var SubmyttedValue = db.QueryValue(selectQueryString, UserId);
There is a method created specifically for this purpose called QuerySingle - just change your query like this:
var data = db.QuerySingle(selectQueryString, UserId);
I hope this helps!
Change your query like this:
Select SubmittedBy FROM Posts WHERE UserId=#0 LIMIT 1

How to serialise ember date?

I'm new to ember and I want to post a new record, So I did something like:
App.AdminController = Em.Controller.extend
submit: ->
post = App.Post.createRecord()
post.set('author', $('#author').val())
post.set('title', $('#title').val())
post.set('intro', $('#intro').val())
post.set('description', $('#description').val())
post.set('publishedAt', new Date())
post.get('store').commit()
Everything works like a charm, except the publisedAt attribute e in post request json file is null
I think the problem is due to that I may not serialise it correctly, any idea?
update the model:
App.Post = DS.Model.extend
title: DS.attr('string')
author: DS.attr('string')
intro: DS.attr('string')
description: DS.attr('string')
publishedat:DS.attr('date')
Try using JSON.stringify on the Date object:
post.set('publishedAt', JSON.stringify(new Date()))
For some reason, you can't invoke new Date() inside the .set method. This should work:
var d = new Date();
post.set('publishedAt', d);