创建并保存模型记录
我的代码:
var mongoose= require('mongoose');
mongoose.connect("****");
var db = mongoose.connection;
db.on(‘error’, console.error.bind(console, 'connection error:'));
var personSchema = new mongoose.Schema({
name : String,
age : Number,
favoriteFoods :[String]
});
var Person = mongoose.model(‘Person’, personSchema);
var createAndSavePerson = function(done) {
var mr = new Person({
name: 'Mrdude',
age: 22,
favoriteFoods: ['Ice Creame', 'Grills']})
mr.save(function(err, mr) {
if(err) return console.error(err);
});
done(null, mr);
};
我找不到此错误
我收到“无法读取null的属性'名称'”错误
请指出我错了
答案 0 :(得分:0)
您需要添加以下行:
function Step({ number, status="NOT_DONE" }) {
switch (status) {
case "DONE":
return <div className="done"><i className="fas fa-check"/></div>
case "CURRENT":
return <div className="active">{number}</div>
case "NOT_DONE":
default:
return <div className="not-done">{number}</div>
}
}
function ProgressBar({ numberOfSteps = 0, currentStep = 0 }) {
if (!numberOfSteps) return null;
const steps = [];
for (let i = 0; i < numberOfSteps; i++) {
const status = i < currentStep ? 'DONE' : i === currentStep ? 'CURRENT' : 'NOT_DONE';
steps.push(<Step number={i} status={status} />)
}
return (
<div>
{steps}
</div>
)
}
答案 1 :(得分:0)
var mongoose= require('mongoose');
mongoose.connect("****");
var db = mongoose.connection;
db.on(‘error’, console.error.bind(console, 'connection error:'));
var personSchema = new mongoose.Schema({
name : String,
age : Number,
favoriteFoods :[String]
});
var Person = mongoose.model(‘Person’, personSchema);
var createAndSavePerson = function(done) {
var mr = new Person({
name: 'Mrdude',
age: 22,
favoriteFoods: ['Ice Creame', 'Grills']})
mr.save(function(err,data) {
if(err)
{
done(err);
}
else
{
done(null, data);
}
});
};
现在工作正常,我在回调函数中犯了一个错误,因此无法访问属性。我返回的是不正确的“先生”。
答案 2 :(得分:0)
您将回调函数放置在错误的位置。
您的done
是回调函数,传递给createAndSavePerson
,因此save
完成时应调用它。
var mongoose= require('mongoose');
mongoose.connect("****");
var db = mongoose.connection;
db.on(‘error’, console.error.bind(console, 'connection error:'));
var personSchema = new mongoose.Schema({
name : String,
age : Number,
favoriteFoods :[String]
});
var Person = mongoose.model(‘Person’, personSchema);
var createAndSavePerson = function(done) {
var mr = new Person({
name: 'Mrdude',
age: 22,
favoriteFoods: ['Ice Creame', 'Grills']})
mr.save(function(err, mr) {
return done(err, mr);
});
// Wrong position
// done(null, mr);
};
// Call function when you need
createAndSave((err, data) => {
if (err) console.log(err);
else console.log(data);
})