When saving from node.js to mongodb, is there a way to save it so that it doesn't overlap?

Asked 2 years ago, Updated 2 years ago, 146 views

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var schema = new Schema({
  name: {type: String, required: true, unique: true},
  img: {type: String, required: true},
  field: {type: String, required: true},
  amount: {type: String, required: true}
}, {
  toJSON: {virtuals: true },
  toObject: {virtuals: true}
});

var Recipe_name = mongoose.model('Recipe_name', schema);

module.exports = Recipe_name;

The model was defined using the mongoose module.

If you put the unique: true attribute, shouldn't it be deduplicated and saved when you save it in the DB?

I keep saving duplicate values... Is there any other way?

for(var i in obj) {
    (function(i) {
        saveRecipeName(obj[i].name, obj[i].img, obj[i].field, obj[i].amount);
    })(i);
}
function saveRecipeName(name, img, field, amount) {
  var recipe_name = new Recipe_name({
    name: name,
    img: img,
    field: field,
    amount: amount
  });
  recipe_name.save(function(error) {
    if(error) {
      console.log(error);
    } } else {
      console.log('save recipe_name: '+name);
    }
  });
}

The code you save has been implemented as above.

It's my first time using a node, so it might be a bit messyㅠ<

node.js mongodb data

2022-09-22 15:35

1 Answers

It's a self-answer.

function save(id, title, callback) {
    Value.findOneAndUpdate(
       {id: id, title: title}, /* query */
       {id: id, title: title}, /* update */
       { { upsert: true}, /* create if it doesn't exist */
       callback);
}

Find it this way through findOneAndUpdate

If you give the updert: true property, it will only be created if it is not in the DB.

Reference link: StackOverFlow


2022-09-22 15:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.