logo
down
shadow

Append inside Schemaless Array


Append inside Schemaless Array

By : Goku Son
Date : November 17 2020, 01:00 AM
wish helps you Despite your schema that error at the top means that that there is a matching document in the collection that does not have this field set as an array, but it's present with another type. Possibly just a string or object.
Here's a little, contrived example listing to demonstrate:
code :
var async = require('async'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var personSchema = new Schema({
  invitation: []
});

var Person = mongoose.model( 'Person', personSchema );

mongoose.connect('mongodb://localhost/test');

async.waterfall(
  [
    function(callback) {
      Person.remove({},function(err,num) {
        callback(err);
      });
    },

    function(callback) {
      console.log( "Creating" );
      var person = new Person();
      person.save(function(err,person) {
        if (err) callback(err);
        console.log(person);
        callback(err,person);
      });
    },

    function(person,callback) {
      console.log( "Updating" );
      Person.findOneAndUpdate(
        { "_id": person._id },
        { "$push": { "invitation": "something" } },
        function(err,doc) {
          if (err) callback(err);
          console.log(doc);
          callback(err);
        }
      );
    },

    function(callback) {
      console.log( "Upserting" );
      Person.findOneAndUpdate(
        { "name": "bob" },
        { "$set": { "invitation": {} } },
        { "upsert": true },
        function(err,doc) {
          if(err) callback(err);
          console.log(doc);
          callback(err,doc);
        }
      );
    },

    function(bob,callback) {
      console.log( "Failing" );
      Person.findOneAndUpdate(
        { "name": "bob" },
        { "$push": { "invitation": "else" } },
        function(err,doc) {
          if (err) callback(err);
          console.log(doc);
          callback(err);
        }
      );
    }

  ],
  function(err) {
    if (err) throw err;
    console.log( "Done" );
    mongoose.disconnect();

  }
);
Creating
{ __v: 0, _id: 54a18afb345b4efc02f21020, invitation: [] }
Updating
{ _id: 54a18afb345b4efc02f21020,
  __v: 0,
  invitation: [ 'something' ] }
Upserting
{ _id: 54a18afb9997ca0c4a7eb722,
  name: 'bob',
  __v: 0,
  invitation: [ {} ] }
Failing

/home/neillunn/scratch/persons/node_modules/mongoose/lib/utils.js:413
    throw err;
          ^
MongoError: exception: The field 'invitation' must be an array but is of type Object
in document   {_id: ObjectId('54a18afb9997ca0c4a7eb722')}
var util = require('util'),
    async = require('async'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

function logger(label,content) {
  console.log(
    "%s:\n%s\n", label, JSON.stringify( content, undefined, 4 ) );
}

function BaseSchema() {

  Schema.apply(this,arguments);

  this.add({
    name: String,
    createdAt: { type: Date, default: Date.now }
  });

}

util.inherits( BaseSchema, Schema );


var personSchema = new BaseSchema(),
    bossSchema = new BaseSchema({ department: String });

var companySchema = new Schema({
  people: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});


var Person = mongoose.model( 'Person', personSchema ),
    Boss = Person.discriminator( 'Boss', bossSchema ),
    Company = mongoose.model( 'Company', companySchema );

mongoose.connect('mongodb://localhost/test');

async.waterfall(
  [
    function(callback) {
      Company.remove({},function(err,num) {
        callback(err);
      });
    },
    function(callback) {
      Person.remove({},function(err,num) {
        callback(err);
      });
    },
    function(callback) {
      var person = new Person({ name: "Bob" });
      person.save(function(err,person) {
        logger("Person", person);
        callback(err,person);
      });
    },
    function(person,callback) {
      var boss = new Boss({ name: "Ted", department: "Accounts" });
      boss.save(function(err,boss) {
        logger("Boss", boss);
        callback(err,person,boss);
      });
    },
    function(person,boss,callback) {
      var company = new Company();
      company.people.push(person,boss);
      company.save(function(err,company) {
        logger("Stored",company);
        callback(err,company);
      });
    },
    function(company,callback) {
      Company.findById(company.id)
        .populate('people')
        .exec(function(err,company) {
          logger("Polulated",company);
          callback(err);
        });
    }
  ],
  function(err) {
    if (err) throw err;
    mongoose.disconnect();
  }
);
Person:
{
    "__v": 0,
    "name": "Bob",
    "createdAt": "2014-12-29T17:53:22.418Z",
    "_id": "54a1951210a7a1b603161119"
}

Boss:
{
    "__v": 0,
    "name": "Ted",
    "department": "Accounts",
    "__t": "Boss",
    "createdAt": "2014-12-29T17:53:22.439Z",
    "_id": "54a1951210a7a1b60316111a"
}

Stored:
{
    "__v": 0,
    "_id": "54a1951210a7a1b60316111b",
    "people": [
        "54a1951210a7a1b603161119",
        "54a1951210a7a1b60316111a"
    ]
}

Polulated:
{
    "_id": "54a1951210a7a1b60316111b",
    "__v": 0,
    "people": [
        {
            "_id": "54a1951210a7a1b603161119",
            "name": "Bob",
            "__v": 0,
            "createdAt": "2014-12-29T17:53:22.418Z"
        },
        {
            "_id": "54a1951210a7a1b60316111a",
            "name": "Ted",
            "department": "Accounts",
            "__v": 0,
            "__t": "Boss",
            "createdAt": "2014-12-29T17:53:22.439Z"
        }
    ]
}
var util = require('util'),
    async = require('async'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

// Utility
function logger(label,content) {
  console.log(
    "%s:\n%s\n", label,
    util.inspect( content, false, 8, false ) );
}

/*
 * Schemas:
 *
 * you can use a base schema for common fields or just a plain
 * definition
 */

var portalSchema = new Schema(),

    userSchema = new Schema({
      "name": String,
      "age": Number
    }),

    eventSchema = new Schema({
      "place": String,
      "eventDate": { type: Date, default: Date.now }
    });

/*
 * Models
 *
 * there is only one "model" defined and therefore one collection only
 * as everything is comes from a stored __v field with the "Model" name
 * defined in the discriminator
 */

var Portal = mongoose.model( 'Portal', portalSchema ),
    User = Portal.discriminator( 'User', userSchema ),
    Event = Portal.discriminator( 'Event', eventSchema );

/*
 * Then there is the thing that is going to consume the references to the
 * 'Portal' model. The array here references the "base" model.
 */

var otherSchema = new Schema({
  "afield": String,
  "portals": [{ type: Schema.Types.ObjectId, ref: "Portal" }]
});

var Other = mongoose.model( 'Other', otherSchema );

/*
 * Meat:
 *
 * Let's start doing things
 */

mongoose.connect('mongodb://localhost/test');

// Just because we're passing around objects without globals or other scoping
async.waterfall(
  [
    // Start fresh by removing all objects in the collections
    function(callback) {
      Other.remove({},function(err,num) {
        callback(err);
      });
    },
    function(callback) {
      Portal.remove({},function(err,num) {
        callback(err);
      });
    },

    // Create some portal things
    function(callback) {
      var eventObj = new Event({ "place": "here" });
      eventObj.save(function(err,eventObj) {
        logger("Event", eventObj);
        callback(err,eventObj);
      });
    },
    function(eventObj,callback) {
      var userObj = new User({ "name": "bob" });
      userObj.save(function(err,userObj) {
        logger("User", userObj);
        callback(err,eventObj,userObj);
      });
    },

    // Store the references in the array for the Other model
    function(eventObj,userObj,callback) {
      var other = new Other({
        "afield": "something"
      });
      other.portals.push(eventObj,userObj);
      other.save(function(err,other) {
        logger("Other Stored",other);
        callback(err,other);
      });
    },

    // See how it's all really stored
    function(other,callback) {
      Portal.find({},function(err,portals) {
        logger("Portals",portals);
        callback(err,other);
      });
    },

    // But watch the magic here
    function(other,callback) {
      User.find({},function(err,portals) {
        logger("Just Users!",portals);
        callback(err,other);
      });
    },


    // And constructed as one object by populate
    function(other,callback) {
      Other.findById(other.id)
        .populate('portals')
        .exec(function(err,other) {
          logger("Other populated",other);
          console.log("%s: %s",
            "1st Element", other.portals[0].constructor.modelName );
          console.log("%s: %s",
            "2nd Element", other.portals[1].constructor.modelName );

          callback(err);
        });
    }

  ],
  function(err) {
    // It's just a script, so clean up
    if (err) throw err;
    mongoose.disconnect();
  }
);
Event:
{ __v: 0,
  place: 'here',
  __t: 'Event',
  _id: 54a253ec456b169310d131f9,
  eventDate: Tue Dec 30 2014 18:27:40 GMT+1100 (AEDT) }

User:
{ __v: 0,
  name: 'bob',
  __t: 'User',
  _id: 54a253ec456b169310d131fa }

Other Stored:
{ __v: 0,
  afield: 'something',
  _id: 54a253ec456b169310d131fb,
  portals: [ 54a253ec456b169310d131f9, 54a253ec456b169310d131fa ] }

Portals:
[ { _id: 54a253ec456b169310d131f9,
    place: 'here',
    __v: 0,
    __t: 'Event',
    eventDate: Tue Dec 30 2014 18:27:40 GMT+1100 (AEDT) },
  { _id: 54a253ec456b169310d131fa,
    name: 'bob',
    __v: 0,
    __t: 'User' } ]

Just Users!:
[ { _id: 54a253ec456b169310d131fa,
    name: 'bob',
    __v: 0,
    __t: 'User' } ]

Other populated:
{ _id: 54a253ec456b169310d131fb,
  afield: 'something',
  __v: 0,
  portals:
   [ { _id: 54a253ec456b169310d131f9,
       place: 'here',
       __v: 0,
       __t: 'Event',
       eventDate: Tue Dec 30 2014 18:27:40 GMT+1100 (AEDT) },
     { _id: 54a253ec456b169310d131fa,
       name: 'bob',
       __v: 0,
       __t: 'User' } ] }

1st Element: Event
2nd Element: User


Share : facebook icon twitter icon
Partially schemaless Document overwrites schemaless values

Partially schemaless Document overwrites schemaless values


By : Marco Peralta
Date : March 29 2020, 07:55 AM
this will help You'll need to use update just like you did for the Detail. If you just use the native serialization of an entire C# class into a MongoDB collection, you'll overwrite the entire document as you've seen.
code :
public class MyEntry
{
    public ObjectId Id { get; set; }
    public string SimpleHash { get; set; }
    public string GroupIdentifier { get; set; }
}

var update = Update<MyEntry>.Combine(
    Update<MyEntry>.Set(m => SimpleHash, "TheHash!"),
    Update<MyEntry>.Set(m => GroupIdentifier, "MyGroup"));
How loop through array in jQuery and append the values in the array inside an li

How loop through array in jQuery and append the values in the array inside an li


By : James Johnson
Date : March 29 2020, 07:55 AM
wish helps you I have a simple array in jQuery with numbers. The numbers 3, 6, 9, 12, 15 represent a specific location in an unordered list that I want to Insert an html div. So after the 3, 6 , 9, etc li I want to insert a div. This is my jQuery. In my code it seems to only insert the div after the 15th li. How do I insert the div at each specific location and not just the last one? , Try this:
code :
var row = [3, 6, 9, 12, 15];
jQuery.each(row, function(i, val) {
    $('<div>').insertAfter('ul#state-list li:nth-child(' + val + ')');
});
How to append comments array data to inside of a posts array according to postid in php?

How to append comments array data to inside of a posts array according to postid in php?


By : Chit Thae Naing
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I have posts result array and comments results array as follows , You can use array_reduce:
code :
$posts = array_reduce($posts, function ($result, $post) use ($comments) {
    $post['comments'] = array();

    foreach ($comments as $comment) {
        if ($comment['post_id'] != $post['post_id']) {
            continue;
        }
        $post['comments'][] = $comment;
    }

    $result[] = $post;

    return $result;
}, array());
How to append an array inside a linked list with a character of another array

How to append an array inside a linked list with a character of another array


By : Nduthi meister
Date : March 29 2020, 07:55 AM
wish of those help There's no means to append to an array in C, as arrays are, per definition fixed (at compile time) lists of same type elements stored contiguously. Only if you have enough array size, a string (which is some char array which is partially filled by appending a \0 null character at the end of the valid char list) can be appended by simply moving the \0 char one place further (if there's place in the array for a character more) and putting before it the desired char. An example will illustrate this (I'll somewhat simplify to separate the list problem you point that has nothing to do with the appending problem)
Let's have:
code :
char c = 'A';
char array[100] = "The string to be appended with ";
/* check first that array has space to store data */
int l = strlen(array);
if (l + 1 < sizeof array) {
    array[l] = c;
    array[l+1] = '\0';
}
int l = strlen(array); /* number of chars in string */
snprintf(array + l,  /* char pointer at string end */ 
    sizeof array - l, /* the number of chars of space available */
    "%c",  /* format string to print a character */
    c);  /* data character to append */
Append inside Array inside Object - Watson Assistant

Append inside Array inside Object - Watson Assistant


By : user3182338
Date : March 29 2020, 07:55 AM
I hope this helps you . From the snippet it seems you have created an object not an array. If so then do
data.entities[0].value.push(1); where data.entities will first get the entities array from the data object
code :
let data = {
  "intent": [],
  "canonica": [],
  "entities": [{
    "name": [],
    "value": []
  }]
}


data.entities[0].value.push(1);
console.log(data)
Related Posts Related Posts :
  • How to debug Vue application with google chrome
  • html 5 web app cache download complete javascript alert?
  • Ember.js setupController fired only once
  • How to validate a currency input
  • How to convert my Array of data to key & value pair
  • Statistics circles in CSS
  • So I wanted to make a trig solver in javascript?
  • Showing HighCharts series name on x-axis and in legend
  • In Rails, how can we pass parameters in script?
  • Build Fails: `npm rebuild node-sass --force`
  • Angular Datepicker change dateformat
  • Trying to extract data from between two sets of characters
  • Configuring Jest in WebStorm
  • Uncaught Error: Syntax error, unrecognized expression: tr.ec_portfolio_title,
  • JQuery fading in fading out continuously
  • Unexpected end of input (Line 1) and Undefined Function?
  • How to animate the width of a div slowly with jquery
  • JavaScript + RegEx Complications- Searching Strings Not Containing SubString
  • SignalR - Unable to get property 'client' of undefined or null reference
  • full calendar not displaying when loaded (with backbone)
  • Angular: Update service and share data between controllers
  • ReplaceAll Google script
  • Search for matching LI items in separate UL
  • Access arguments of an... argument
  • Customizing Google custom search jsapi (query strings)
  • React | Can´t load Images > Module not found
  • Dynamically creating buttons in DOJO
  • 404 Not Found in AJAX post call
  • How do I find out, using javascript, what software opened and running my application?
  • Javascript to check the status of wireless connection
  • StarDict support for JavaScript and a Firefox OS App
  • Phonegap event Resume
  • call javascript function on ENTER key press?
  • When is the best time to remove no-js classes from the html tag
  • Recommended email sending languages
  • setInterval not working properly with chrome
  • Does IE create new scope for each script tag?
  • Uncaught SyntaxError: Unexpected token < Underscore and parse issues
  • How to pass captured URL to Email Body in HTML
  • How to structure default nested resources?
  • Store all the keys of a JSON object in a variable
  • Need an efficient way to group the Array of object in javascript
  • a sensible approach to highcharts x-axis labels
  • IDE autocompletion for javascript AMD loading style
  • Bootstrap menu disappears after first click setting the ul style to none
  • split ajax json response errors in each field
  • how to add javascript in head in cmsms
  • REGEX: Finding the correct occurrence order of some given special characters in a string
  • How do you preserve a JavaScript date's time zone from browser to server, and back?
  • Return binary result from phantomjs webserver
  • must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.
  • Replacing a substring of an element's text with another string
  • How do I filter marks greater than or equal to 90 in this array?
  • Modify the text of my radio input button?
  • Clicking on status bar does not scroll to top of app (Trigger.io)
  • Mocha JS: How to highlight specific assertion failure?
  • $.getJSON jquery parsing to HTML
  • Find items of a certain class (a) that are also in other classes (b,c,d)
  • Setting different images for D3 force-directed layout nodes
  • Integrating Dropzone.js with angular
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org