最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What does mongoose.save() return and is it useful? - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 1

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

  • Mongooose Introduction
  • API Docs
发布评论

评论列表(0)

  1. 暂无评论