Praneeth Wanigasekera
Praneeth Wanigasekera

Reputation: 946

findAndModify MongoDB insert element at beginning of array

Update: Problem here was that the native MongoDB driver needed the objectID in a different format than Mongoose. Instead of {_id: story_id} I needed to do, {_id: new mongoose.Types.ObjectId(story_id)}. The reason it returned just the two fields was that it was creating a new document with {_id: story_id} rather than updating the document which was {_id: {$oid: story_id}}. However, my original reason for doing this with the native driver vs. mongoose turned out to not work. Even the native driver does not accept positive $slice values. So I'm still looking for a way to insert an object to the beginning of an array using Mongoose or the native driver accessed through Mongoose (which does not support $position or positive $slice values).

When I run the query below, the returned results only include _id, messages and participants. I would like to get the full story record back rather than just the updated fields. Is there a way to do this? Based on Node MongoDB Native driver documentation (http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#findandmodify) the "fields" parameter from the mongo console is not implemented in the findAndModify driver. I want to avoid having to do a second query to get the just updated record.

Story.collection.findAndModify(
{"_id": story_id},
{"_id": "asc"},
{ 
    "$push": {
"messages": {
  "$each": [message],
  "$sort": { "_id": -1},
  "$slice": 500 
    },
  },
    "$addToSet": {"participants": user_id},
},
    {new: true},
    {fields: {"feeling":1, "description":1, "image_height":1, "image_width":1, "storyteller":1, "image_url":1, "participants":1}},   // -> this line is ignored by MongoDB native driver

      {upsert: true}

)

Upvotes: 2

Views: 1920

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312035

You can insert elements at the beginning of an array field with a $push that uses the $each and $position modifiers (which is supported by Mongoose):

Story.findByIdAndUpdate(story_id, {
    $push: {
      messages: {
        $each: [message],
        $position: 0
      },
    },
    $addToSet: {participants: user_id},
  }, {
    new: true,
    upsert: true
  },
  function (err, newDoc) { ... }
);

Upvotes: 3

Related Questions