简体   繁体   中英

MongoDB and mongoose: how to add an object if it doesn't already exist

I am having some trouble with mongoDB/mongoose and node.js. I am used to SQL, and mongoDB is...hard! Here is my schema:

var mongoose = require('mongoose');

mongoose.Promise = global.Promise;

var itemSchema= mongoose.Schema({

    item_info        : {
        user_id      : Number,
        location     : String,
        item_id      : Number,
        title        : String
    },
    item_hist        : {
        user_id      : Number,
        location     : String,
        item_id      : Number,
        founddate    : String
       }
});
module.exports = mongoose.model('item', itemSchema);

And I can add a new item by doing this:

    var item= require('./app/models/item');
    var item= new item();
    item.item_info.user_id      =  12345;
    item.item_info.location     = 'This address';
    item.item_info.item_id      = 4444;
    item.item_info.title        = 'New item';
    item.save(function(err) 
    {
        if (err)    throw err;
    });

What I want to be able to do is say: "look for an item with item_info.item_id 5555. if it exists, do nothing. if it doesn't exist, then add it to the database." I've read through so much mongodb and mongoose documentation, but between using dot notation and accessing through nodejs instead of command line mongodb, I still can't figure out how to do this. SQL seemed so much easier!

Just use this -

    var query = { user_id: 12345, location: "This address", item_id: 4444, title: "New item"  },

        options = { upsert: true };

   Model.findOneAndUpdate(query.item_id, query, options, function(error, result) {
    if (error) return;

    // do something with the document
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM