update with $set insert new record

`db = {};
db.userMessages = new Datastore(‘path/to/messages.db’);
db.settings = new Datastore(“path/to/settings.db”);
db.userMessages.loadDatabase();
db.settings.loadDatabase();

var doc={
“name”:”setting”,
“messageCounter”:101
}
db.settings.insert(doc,function(err,doc)
{

})

db.settings.find({name:’setting’},function (err,doc) {
console.log(doc)
});

db.settings.update({ name: ‘setting’}, { $set: { messageCounter: 129 } }, {}, function (err, numReplaced) {
console.log(numReplaced);
});

give me this document
{“name”:”setting”,”messageCounter”:101,”_id”:”mzau1St5zaPBmf4D”}
{“name”:”setting”,”messageCounter”:129,”_id”:”mzau1St5zaPBmf4D”}
`
insert new same record with change my field what can i do?

1 possible answer(s) on “update with $set insert new record

  1. When you say that it “gives you” this:

    {"name":"setting","messageCounter":101,"_id":"mzau1St5zaPBmf4D"}
    {"name":"setting","messageCounter":129,"_id":"mzau1St5zaPBmf4D"}
    

    …where are you getting that from?

    My assumption is that you are looking at the actual file contents, which are mostly irrelevant. NeDB operates by pushing to the file in an append-only format, and all duplicates and meta-records are consolidated during compaction (or after the initial load). See the README for more details.

    If you did a db.settings.find({ name: 'setting' }) rather than looking at the file contents, it would only return you a single document. As you can see, both records you pasted do share the same ID as well, so you can be certain that it is a single record rather than an incorrect second record.