Reputation: 1019
I am updating a record via Mongoose but when I try to not include a field by not including it in the properties object the field just gets set to empty.
My model:
var demo = new Schema({
name: String,
slug: String,
code: String,
details: String,
scripts: [],
css: [],
status: {
type: String,
default: "draft"
},
lastModifiedDate: {
type: Date,
default: Date.now
},
projectId: Schema.ObjectId
});
Where I'm saving:
Demo.find({ slug: req.params.demoSlug }, function(err,demos){
if(err){
console.log("Error retrieving demo from db");
res.send(500,err);
return;
}
demos[0].update({ _id:req.params.id },{
name: data.demoName,
slug: Utils.createSlug(data.demoName),
// code: data.demoCode,
details: data.demoDetails
}, someCallback);
});
As you can see the "code" field is commented out so why is the field value being overridden? Are there any flags I need to set when
Upvotes: 2
Views: 2994
Reputation: 7464
It's not clear exactly what you're trying to do. You're searching for every document in a collection, but you're only updating one of them, which you're finding by _id
. This looks like it can be done in one function, and you could be getting an error because you're calling update
on a model that you returned. It looks like you should have written it like this:
Demo.update({ _id:req.params.id },{
name: data.demoName,
slug: Utils.createSlug(data.demoName),
// code: data.demoCode,
details: data.demoDetails
}, someCallback);
If you only want to update the document if its slug matches your demoSlug
AND the _id
matches, it would look like this:
Demo.update({ _id: req.params.id, slug: req.params.demoSlug },{
name: data.demoName,
slug: Utils.createSlug(data.demoName),
// code: data.demoCode,
details: data.demoDetails
}, someCallback);
If this still doesn't address your problem, hopefully it helps you explain more clearly what exactly you're looking for.
EDIT:
Another way to do this would be to use findOne
and save
. Try this:
Demo.findOne({ slug: req.params.demoSlug }, function(err, demo) {
if(err) {
console.log("Error retrieving demo from db");
res.send(500, err);
return;
}
demo.name = data.demoName;
demo.slug = Utils.createSlug(data.demoName);
demo.details = data.demoDetails;
demo.save(callback);
}
Something like that should hopefully work. If neither of these work, I suspect that the problem is in data
or in the document you're finding.
Upvotes: 2