0

当 dbUser 被实例化并在同一个实例中给定值时,可以调用函数 dbUser.save 将数据输入到 localhost:mongodb。

var gmailUserSchema = new mongoose.Schema({
displayName: String,
emails: [ { value: String } ],
name: { familyName: String, givenName: String } 
})

// compiling our schema into a Model.
var gmailUser = mongoose.model('gmailUser', gmailUserSchema);
var dbUser = new gmailUser ({
                displayName: 'profile.displayName',
                emails: [{value: 'profile.emails'}] ,
                name: { familyName: 'profile.familyName',
                givenName: 'profile.givenName' }
            });

dbUser.save(function (err) {
  if (err) // ...
  console.log('could not save');
});

但是,如果我将值放入与构造函数分开的“dbUser”中。

// defining schema 
var gmailUserSchema = new mongoose.Schema({
displayName: String,
emails: [ { value: String } ],
name: { familyName: String, givenName: String } 
})

// compiling our schema into a Model.
var gmailUser = mongoose.model('gmailUser', gmailUserSchema);
var dbUser = new gmailUser;

dbUser = {
                displayName: '1profile.displayName',
                emails: [{value: '1profile.emails'}] ,
                name: { familyName: '1profile.familyName',
                givenName: '1profile.givenName' }
}


dbUser.save(function (err) {
 if (err) // ...
 console.log('could not save');
});

编译时出现以下错误:

dbUser.save(function (err) {
       ^
TypeError: Object #<Object> has no method 'save'
    at Object.<anonymous> (/Users/apple/Documents/herokuApp/onlymongoose-3.js:65:8)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
4

1 回答 1

0

执行此操作时,您正在替换原始 dbUser 对象:

var dbUser = new gmailUser;

dbUser = {
                displayName: '1profile.displayName',
                emails: [{value: '1profile.emails'}] ,
                name: { familyName: '1profile.familyName',
                givenName: '1profile.givenName' }
}

您可以通过执行以下操作单独更新字段:

dbUser.displayName = '1profile.displayName';
dbUser.emails = [{value: '1profile.emails'}];
dbUser.name = { familyName: '1profile.familyName' };
dbUser.givenName = '1profile.givenName';
于 2013-07-24T17:02:54.797 回答