Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

native update in Sails with Mongo does not work with ObjectId

I wonder what I am doing wrong.

I use Sailsv0.10 and mongo2.6.0 and want to update an array field (using $push) in a collection via native.

My model:

module.exports = {

schema: true,
attributes: {

  username: {
    type: 'string',
    required: true
  },
  pubs: {
    type: 'array',
    defaultsTo: []
  },
  ...

My function:

    User.native(function (err, collection) {
      collection.update({username:aUsernameVariable},{$push:{pubs:aPubsVariable}}, function (err) {
    });

It works so far. But why does that not work as a query with the id field?

    User.native(function (err, collection) {
      collection.update({id:anIdVariable},{$push:{pubs:aPubsVariable}}, function (err) {
    });

I definately use the right id for the query to test it.

What am I doing wrong? Or is that a ObjectId type conversion Problem of the Sails-Mongo Adapter

like image 582
user3707805 Avatar asked Nov 30 '22 11:11

user3707805


2 Answers

If you want to use native() you can always try the same query directly in your mongo-DB. Because _id is a Object-id you should

var ObjectId = require('mongodb').ObjectID;

 User.native(function (err, collection) {
  collection.update({_id: new ObjectId(anIdVariable)},{$push:{pubs:aPubsVariable}}, function (err) {
});

You can add the mongo-native-driver to you app with npm install mongodb --save

like image 131
mdunisch Avatar answered Feb 23 '23 17:02

mdunisch


if you use sailsjs then:

ObjectID = require('sails-mongo/node_modules/mongodb').ObjectID;
var o_id = new ObjectID(req.param('id'));
console.log(o_id );

:)

[email protected]

like image 24
Richard Avatar answered Feb 23 '23 19:02

Richard