1

Is there a way that whenever I $push a new element in monodb array, a normal _id is added to it? I remember that mongoose was doing something like that automatically but now I am using mongodb's native js and it seems to be not inserting any _id.

Example:

chats.updateOne({_id: chat_id},
            {$push: {messages: 
                    {
                        message: data.message,
                        date: new Date(),
                    }}},
            function(err, response){}
)};

On executing, messages array should have regular _id field, message and date. Currently it only creates message and date.

1
  • You need to create schema for messages Commented Jan 28, 2016 at 14:49

1 Answer 1

3

You can use ObjectId():

chats.updateOne({_id: chat_id},
            {$push: {messages: 
                    {
                        message: data.message,
                        date: new Date(),
                        _id: ObjectId()
                    }}},
            function(err, response){}
)};
Sign up to request clarification or add additional context in comments.

1 Comment

ObjectId() is not the same function in NodeJS driver as in mongo Shell. Alternative is ObjectID.createFromTime(time). Just to help the future visitors. Docs: mongodb.github.io/node-mongodb-native/api-bson-generated/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.