ECMAScript
ECMAScript

Reputation: 4649

How do I use findAndModify()? to push an array?

My userSchema is:

module.exports = mongoose.model('users', {
    userName: String,
    messages: Array 
});

Messages will be:

messages: [{msg: "foo", time: new Date()},{msg: "Bar", time: new Date()}]

I want to be able to create a new record if there is no match userName, or if it is found, array.push the msg and time into the DB.

userSchema.findAndModify({
    query:{userName: "Test"},
    update:{$push: {messages: {msg: "foo", time: new Date()}}},
});

I'm assuming this is correct, how would I add a new user if there is no found userName?

Upvotes: 1

Views: 1808

Answers (1)

Piyas De
Piyas De

Reputation: 1764

Assuming your above query is true,

Your above query should have upsert:true

Like

userSchema.findAndModify({ query:{userName: "Test"}, update:{$push: {messages: {msg: "foo", time: new Date()}}}, new: true,
upsert : true });

Here new indicates returning the updated or inserted object. upsert indicates inserting a new record or updating a record depending on the record existence criteria.

Now when you push first message, if the username does not exists, then it will automatically be inserted.

Otherwise if you want to insert other attributes of user, you should use update: { $set: command.

Hope it will help you.

Thanks

Upvotes: 2

Related Questions