简体   繁体   中英

What does mongoose.save() return and is it useful?

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();  
};

The 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:-

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