I know that the return value is a promise, but was curious as to what temp1
is in this case. Currently is is returning undefined
.
let temp = DBM.saveArticle(obj).then(() => {
});
debug && console.log('DEBUG: /articles/add: temp ', temp);
temp.then((temp1)=>{
debug && console.log('DEBUG: /articles/add: temp ', temp1);
})
uses:
// Create operations
const saveInstance = (name, schema, obj) => {
const Model = mongoose.model(name, schema);
return new Model(obj).save();
};
I know that the return value is a promise, but was curious as to what temp1
is in this case. Currently is is returning undefined
.
let temp = DBM.saveArticle(obj).then(() => {
});
debug && console.log('DEBUG: /articles/add: temp ', temp);
temp.then((temp1)=>{
debug && console.log('DEBUG: /articles/add: temp ', temp1);
})
uses:
// Create operations
const saveInstance = (name, schema, obj) => {
const Model = mongoose.model(name, schema);
return new Model(obj).save();
};
Share
edited Dec 8, 2020 at 4:39
asked Nov 27, 2020 at 4:22
user14704144user14704144
2 Answers
Reset to default 1The save() method is asynchronous, and according to the docs, it returns undefined if used with callback or a Promise otherwise.
So, if you want to read the created value you have to await for the promise return. In your case, wait for the value from saveInstance
returned promise. You can do this two ways.
Using await inside an async function:
let created = await saveInstance(name, schema, obj);
console.log(created);
Or use it with then
:
saveInstance(name, schema, obj).then(function(value) {
console.log(value);
}
save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on.
When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.
const Person = mongoose.model('Person', Schema({
name: String,
age: Number
}));
const doc = await Person.create({ name: 'Will Riker', age: 29 });
// Setting `age` to an invalid value is ok...
doc.age = 'Lollipop';
// But trying to `save()` the document errors out
const err = await doc.save().catch(err => err);
err; // Cast to Number failed for value "Lollipop" at path "age"
// But then `save()` succeeds if you set `age` to a valid value.
doc.age = 30;
await doc.save();
Attaching few reference links here:-
- Mongooose Introduction
- API Docs